/* 
	
CODE TO PRODUCE TABLES

Tables produced in this code:

Table 1
Table 2
Table 3
Table 4
Table 5
Table 6
Table 7

Appendix Table A3
Appendix Table A4
Appendix Table A5
Appendix Table A6
Appendix Table A7
Appendix Table A8
Appendix Table A9
Appendix Table C1
Appendix Table D1
Appendix Table D2

*/

********************************************************************************
* set directories
********************************************************************************
global input = "..\Input_data\" // set path for data/input files
global out = "..\Output\" // set path for output (tables/figures)

********************************************************************************
* open data and initial processing
********************************************************************************
use "${input}planb_rdsmpl.dta", clear

/*
	TABLE 2 USING FILE WRITE
	Creates a properly formatted CSV matching your Excel layout
*/

********************************************************************************
* Settings
********************************************************************************
global donut="donut==0"
global bw10 "inrange(x,104,126) & donut==0" 
global bw8 "inrange(x,106,124) & donut==0" 
global bw6 "inrange(x,108,122) & donut==0" 
gen x=r+116 // rescale running variable

********************************************************************************
* Open file and write header
********************************************************************************
file close _all
file open table using "$out\table_2_formatted.csv", write replace

* Write column headers
file write table "," "(1)," "(2)," "(3)," "," "(4)," "," "(5)," "," "(6)" _n
file write table "," "Baseline (Pre-gifted) Measures," "," "," "First-Stage," "Reduced Form," "2SLS" _n
file write table "," "Grade 2 average z-score (Math and Reading)," ///
                 "Grade 3 average z-score (Math and Reading)," ///
                 "Predicted On-time Enrollment," "," ///
                 "Probability of being Gifted," "," ///
                 "Grad HS On-time + Enrolled Within 1 Year," "," ///
                 "Grad HS On-time + Enrolled Within 1 Year" _n

********************************************************************************
* Panel A: Boys
********************************************************************************

file write table "Panel A. Boys Only" _n

* Loop through bandwidths: 8, 6, 10
foreach bw in 8 6 10 {
    
    * Initialize storage for this bandwidth
    local coef_g2 = ""
    local se_g2 = ""
    local n_g2 = ""
    local coef_g3 = ""
    local se_g3 = ""
    local n_g3 = ""
    local coef_pr = ""
    local se_pr = ""
    local n_pr = ""
    local coef_fs = ""
    local se_fs = ""
    local sig_fs = ""
    local n_fs = ""
    local coef_rf = ""
    local se_rf = ""
    local sig_rf = ""
    local n_rf = ""
    local coef_2sls = ""
    local se_2sls = ""
    local sig_2sls = ""
    local n_2sls = ""
    
    * Column 1: Grade 2 z-score (baseline)
    reg g2_zscore r d dxr if $donut & ${bw`bw'} & m==1, cluster(schid)
    local coef_g2 = string(_b[d], "%4.2f")
    local se_g2 = string(_se[d], "%4.2f")
    local n_g2 = e(N)
    
    * Column 2: Grade 3 z-score (baseline)
    reg g3fcat r d dxr if $donut & ${bw`bw'} & m==1, cluster(schid)
    local coef_g3 = string(_b[d], "%4.2f")
    local se_g3 = string(_se[d], "%4.2f")
    local n_g3 = e(N)
    
    * Column 3: Predicted on-time enrollment (baseline)
    reg pr_collot r d dxr if $donut & ${bw`bw'} & m==1, cluster(schid)
    local coef_pr = string(_b[d], "%4.2f")
    local se_pr = string(_se[d], "%4.2f")
    local n_pr = e(N)
    
    * Column 4: First stage (gifted)
    reg gifted r d dxr if $donut & ${bw`bw'} & m==1, cluster(schid)
    local coef_fs = string(_b[d], "%4.2f")
    local se_fs = string(_se[d], "%4.2f")
    local n_fs = e(N)
    test d
    local p_fs = r(p)
    if `p_fs' < 0.01 local sig_fs = "**"
    else if `p_fs' < 0.05 local sig_fs = "*"
    else if `p_fs' < 0.10 local sig_fs = "+"
    else local sig_fs = ""
    
    * Column 5: Reduced form (collot)
    reg collot r d dxr if $donut & ${bw`bw'} & m==1, cluster(schid)
    local coef_rf = string(_b[d], "%4.2f")
    local se_rf = string(_se[d], "%4.2f")
    local n_rf = e(N)
    test d
    local p_rf = r(p)
    if `p_rf' < 0.01 local sig_rf = "**"
    else if `p_rf' < 0.05 local sig_rf = "*"
    else if `p_rf' < 0.10 local sig_rf = "+"
    else local sig_rf = ""
    
    * Column 6: 2SLS
    xi: ivreg collot (gifted = r d dxr) r dxr if $donut & ${bw`bw'} & m==1, cluster(schid)
    local coef_2sls = string(_b[gifted], "%4.2f")
    local se_2sls = string(_se[gifted], "%4.2f")
    local n_2sls = e(N)
    test gifted
    local p_2sls = r(p)
    if `p_2sls' < 0.01 local sig_2sls = "**"
    else if `p_2sls' < 0.05 local sig_2sls = "*"
    else if `p_2sls' < 0.10 local sig_2sls = "+"
    else local sig_2sls = ""
    
    * Write bandwidth label and coefficients
    file write table "BW `bw'," ///
                     "`coef_g2'," ///
                     "`coef_g3'," ///
                     "`coef_pr'," "," ///
                     "`coef_fs'`sig_fs'," "," ///
                     "`coef_rf'`sig_rf'," "," ///
                     "`coef_2sls'`sig_2sls'" _n
    
    * Write standard errors
    file write table "," ///
                     "(" "`se_g2'" ")," ///
                     "(" "`se_g3'" ")," ///
                     "(" "`se_pr'" ")," "," ///
                     "(" "`se_fs'" ")," "," ///
                     "(" "`se_rf'" ")," "," ///
                     "(" "`se_2sls'" ")" _n
    
    * Write blank row
    file write table "," "," "," "," "," "," "," "," "," _n
    
    * Write observations
    file write table "Obs.," ///
                     "`n_g2'," ///
                     "`n_g3'," ///
                     "`n_pr'," "," ///
                     "`n_fs'," "," ///
                     "`n_rf'," "," ///
                     "`n_2sls'" _n
    
    * Write blank row between bandwidths
    file write table "," "," "," "," "," "," _n
}

********************************************************************************
* Panel B: Girls
********************************************************************************

file write table "Panel B. Girls Only" _n

* Loop through bandwidths: 8, 6, 10
foreach bw in 8 6 10 {
    
    * Initialize storage
    local coef_g2 = ""
    local se_g2 = ""
    local n_g2 = ""
    local coef_g3 = ""
    local se_g3 = ""
    local n_g3 = ""
    local coef_pr = ""
    local se_pr = ""
    local n_pr = ""
    local coef_fs = ""
    local se_fs = ""
    local sig_fs = ""
    local n_fs = ""
    local coef_rf = ""
    local se_rf = ""
    local sig_rf = ""
    local n_rf = ""
    local coef_2sls = ""
    local se_2sls = ""
    local sig_2sls = ""
    local n_2sls = ""
    
    * Column 1: Grade 2 z-score
    reg g2_zscore r d dxr if $donut & ${bw`bw'} & f==1, cluster(schid)
    local coef_g2 = string(_b[d], "%4.2f")
    local se_g2 = string(_se[d], "%4.2f")
    local n_g2 = e(N)
    
    * Column 2: Grade 3 z-score
    reg g3fcat r d dxr if $donut & ${bw`bw'} & f==1, cluster(schid)
    local coef_g3 = string(_b[d], "%4.2f")
    local se_g3 = string(_se[d], "%4.2f")
    local n_g3 = e(N)
    
    * Column 3: Predicted on-time enrollment
    reg pr_collot r d dxr if $donut & ${bw`bw'} & f==1, cluster(schid)
    local coef_pr = string(_b[d], "%4.2f")
    local se_pr = string(_se[d], "%4.2f")
    local n_pr = e(N)
    
    * Column 4: First stage
    reg gifted r d dxr if $donut & ${bw`bw'} & f==1, cluster(schid)
    local coef_fs = string(_b[d], "%4.2f")
    local se_fs = string(_se[d], "%4.2f")
    local n_fs = e(N)
    test d
    local p_fs = r(p)
    if `p_fs' < 0.01 local sig_fs = "**"
    else if `p_fs' < 0.05 local sig_fs = "*"
    else if `p_fs' < 0.10 local sig_fs = "+"
    else local sig_fs = ""
    
    * Column 5: Reduced form
    reg collot r d dxr if $donut & ${bw`bw'} & f==1, cluster(schid)
    local coef_rf = string(_b[d], "%4.2f")
    local se_rf = string(_se[d], "%4.2f")
    local n_rf = e(N)
    test d
    local p_rf = r(p)
    if `p_rf' < 0.01 local sig_rf = "**"
    else if `p_rf' < 0.05 local sig_rf = "*"
    else if `p_rf' < 0.10 local sig_rf = "+"
    else local sig_rf = ""
    
    * Column 6: 2SLS
    xi: ivreg collot (gifted = r d dxr) r dxr if $donut & ${bw`bw'} & f==1, cluster(schid)
    local coef_2sls = string(_b[gifted], "%4.2f")
    local se_2sls = string(_se[gifted], "%4.2f")
    local n_2sls = e(N)
    test gifted
    local p_2sls = r(p)
    if `p_2sls' < 0.01 local sig_2sls = "**"
    else if `p_2sls' < 0.05 local sig_2sls = "*"
    else if `p_2sls' < 0.10 local sig_2sls = "+"
    else local sig_2sls = ""
    
    * Write bandwidth label and coefficients
    file write table "BW `bw'," ///
                     "`coef_g2'," ///
                     "`coef_g3'," ///
                     "`coef_pr'," "," ///
                     "`coef_fs'`sig_fs'," "," ///
                     "`coef_rf'`sig_rf'," "," ///
                     "`coef_2sls'`sig_2sls'" _n
    
    * Write standard errors
    file write table "," ///
                     "(" "`se_g2'" ")," ///
                     "(" "`se_g3'" ")," ///
                     "(" "`se_pr'" ")," "," ///
                     "(" "`se_fs'" ")," "," ///
                     "(" "`se_rf'" ")," "," ///
                     "(" "`se_2sls'" ")" _n
    
    * Write blank row
    file write table "," "," "," "," "," "," "," "," "," _n
    
    * Write observations
    file write table "Obs.," ///
                     "`n_g2'," ///
                     "`n_g3'," ///
                     "`n_pr'," "," ///
                     "`n_fs'," "," ///
                     "`n_rf'," "," ///
                     "`n_2sls'" _n
    
    * Write blank row between bandwidths
    file write table "," "," "," "," "," "," "," "," "," _n
}

* Close file
file close table

display ""
display "Table 2 created: $out\table_2_formatted.csv"
display ""

********************************************************************************
*** TABLE 3
********************************************************************************

/*
    TABLE 3 USING FILE WRITE
    Courses/Mediators - 2SLS estimates
*/

********************************************************************************
* Settings
********************************************************************************

global donut = "donut==0"
global bw10  "inrange(x,104,126) & donut==0" 
global bw8   "inrange(x,106,124) & donut==0" 
global bw6   "inrange(x,108,122) & donut==0" 

********************************************************************************
* Open file and write header
********************************************************************************

file close _all
file open table using "$out\table_3_formatted.csv", write replace

* Column headers
file write table "," "(1)" "," "(2)" "," "(3)" "," "(4)" "," "(5)" _n
file write table "," ///
    "Gifted/High Achiever Classroom" "," ///
    "GEM Eligible" "," ///
    "GEM in Grade 6" "," ///
    "Algebra in Grade 8" "," ///
    "Number of AP Courses" _n


********************************************************************************
* Panel A: Boys
********************************************************************************

file write table "Panel A. Boys Only" _n

foreach bw in 8 6 10 {

    * ----- Column 1: GHA classroom -----
    xi: ivreg gha (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_gha  = string(_b[gifted], "%4.2f")
    local se_gha = string(_se[gifted], "%4.2f")
    local N_gha  = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_gha = "**"
    else if `p' < 0.05 local sig_gha = "*"
    else if `p' < 0.10 local sig_gha = "+"
    else                local sig_gha = ""

    * ----- Column 2: GEM eligible -----
    xi: ivreg gemelig (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_gemelig  = string(_b[gifted], "%4.2f")
    local se_gemelig = string(_se[gifted], "%4.2f")
    local N_gemelig  = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_gemelig = "**"
    else if `p' < 0.05 local sig_gemelig = "*"
    else if `p' < 0.10 local sig_gemelig = "+"
    else                local sig_gemelig = ""

    * ----- Column 3: GEM in grade 6 -----
    xi: ivreg gem6 (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_gem6  = string(_b[gifted], "%4.2f")
    local se_gem6 = string(_se[gifted], "%4.2f")
    local N_gem6  = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_gem6 = "**"
    else if `p' < 0.05 local sig_gem6 = "*"
    else if `p' < 0.10 local sig_gem6 = "+"
    else                local sig_gem6 = ""

    * ----- Column 4: Algebra in grade 8 -----
    xi: ivreg alg8 (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_alg8  = string(_b[gifted], "%4.2f")
    local se_alg8 = string(_se[gifted], "%4.2f")
    local N_alg8  = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_alg8 = "**"
    else if `p' < 0.05 local sig_alg8 = "*"
    else if `p' < 0.10 local sig_alg8 = "+"
    else                local sig_alg8 = ""

    * ----- Column 5: # AP courses -----
    xi: ivreg num_ap_course (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_ap  = string(_b[gifted], "%4.2f")
    local se_ap = string(_se[gifted], "%4.2f")
    local N_ap  = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_ap = "**"
    else if `p' < 0.05 local sig_ap = "*"
    else if `p' < 0.10 local sig_ap = "+"
    else                local sig_ap = ""

    * ----- Coefficient row -----
    file write table "BW `bw'" "," ///
        `"`b_gha'`sig_gha'"' "," ///
        `"`b_gemelig'`sig_gemelig'"' "," ///
        `"`b_gem6'`sig_gem6'"' "," ///
        `"`b_alg8'`sig_alg8'"' "," ///
        `"`b_ap'`sig_ap'"' _n

    * ----- SE row -----
    file write table "," ///
        "(" `"`se_gha'"' ")" "," ///
        "(" `"`se_gemelig'"' ")" "," ///
        "(" `"`se_gem6'"' ")" "," ///
        "(" `"`se_alg8'"' ")" "," ///
        "(" `"`se_ap'"' ")" _n

    * ----- Obs row -----
    file write table "Obs." "," ///
        "`N_gha'" "," ///
        "`N_gemelig'" "," ///
        "`N_gem6'" "," ///
        "`N_alg8'" "," ///
        "`N_ap'" _n

    * Blank row
    file write table "," "," "," "," "," _n
}

********************************************************************************
* Panel B: Girls
********************************************************************************

file write table "Panel B. Girls Only" _n

foreach bw in 8 6 10 {

    * ----- Column 1: GHA classroom -----
    xi: ivreg gha (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_gha  = string(_b[gifted], "%4.2f")
    local se_gha = string(_se[gifted], "%4.2f")
    local N_gha  = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_gha = "**"
    else if `p' < 0.05 local sig_gha = "*"
    else if `p' < 0.10 local sig_gha = "+"
    else                local sig_gha = ""

    * ----- Column 2: GEM eligible -----
    xi: ivreg gemelig (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_gemelig  = string(_b[gifted], "%4.2f")
    local se_gemelig = string(_se[gifted], "%4.2f")
    local N_gemelig  = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_gemelig = "**"
    else if `p' < 0.05 local sig_gemelig = "*"
    else if `p' < 0.10 local sig_gemelig = "+"
    else                local sig_gemelig = ""

    * ----- Column 3: GEM in grade 6 -----
    xi: ivreg gem6 (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_gem6  = string(_b[gifted], "%4.2f")
    local se_gem6 = string(_se[gifted], "%4.2f")
    local N_gem6  = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_gem6 = "**"
    else if `p' < 0.05 local sig_gem6 = "*"
    else if `p' < 0.10 local sig_gem6 = "+"
    else                local sig_gem6 = ""

    * ----- Column 4: Algebra in grade 8 -----
    xi: ivreg alg8 (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_alg8  = string(_b[gifted], "%4.2f")
    local se_alg8 = string(_se[gifted], "%4.2f")
    local N_alg8  = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_alg8 = "**"
    else if `p' < 0.05 local sig_alg8 = "*"
    else if `p' < 0.10 local sig_alg8 = "+"
    else                local sig_alg8 = ""

    * ----- Column 5: # AP courses -----
    xi: ivreg num_ap_course (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_ap  = string(_b[gifted], "%4.2f")
    local se_ap = string(_se[gifted], "%4.2f")
    local N_ap  = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_ap = "**"
    else if `p' < 0.05 local sig_ap = "*"
    else if `p' < 0.10 local sig_ap = "+"
    else                local sig_ap = ""

	* ----- Coefficient row -----
    file write table "BW `bw'" "," ///
        `"`b_gha'`sig_gha'"' "," ///
        `"`b_gemelig'`sig_gemelig'"' "," ///
        `"`b_gem6'`sig_gem6'"' "," ///
        `"`b_alg8'`sig_alg8'"' "," ///
        `"`b_ap'`sig_ap'"' _n

    * ----- SE row -----
    file write table "," ///
        "(" `"`se_gha'"' ")" "," ///
        "(" `"`se_gemelig'"' ")" "," ///
        "(" `"`se_gem6'"' ")" "," ///
        "(" `"`se_alg8'"' ")" "," ///
        "(" `"`se_ap'"' ")" _n

    * ----- Obs row -----
    file write table "Obs." "," ///
        "`N_gha'" "," ///
        "`N_gemelig'" "," ///
        "`N_gem6'" "," ///
        "`N_alg8'" "," ///
        "`N_ap'" _n

    * Blank row
    file write table "," "," "," "," "," _n
}

* Close file
file close table

display ""
display "Table 3 created: $out\table_3_formatted.csv"
display ""

********************************************************************************
*** TABLE 4 - Course grades and disciplinary actions
********************************************************************************

* Outcomes:
*   (1) Middle school math GPA (grades 6-8)
*   (2) No suspensions in middle school
*   (3) High school math GPA
*   (4) High school language arts GPA
*   (5) Overall high school GPA

file close _all
file open table using "$out\table_4_formatted.csv", write replace

* Header row: (1)-(5)
file write table "," "(1)" "," "(2)" "," "(3)" "," "(4)" "," "(5)" _n

* Header row: labels
file write table "," ///
    "Math GPA Grades 6-8" "," ///
    "No Suspensions Grades 6-8" "," ///
    "HS Math GPA" "," ///
    "HS Language Arts GPA" "," ///
    "Overall HS GPA" _n

********************************************************************************
* Panel A: Boys
********************************************************************************

file write table "Panel A. Boys Only" _n

foreach bw in 8 6 10 {

    * ----- Column 1: Math GPA, Grades 6-8 -----
    xi: ivreg math_gpa_g68 (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_m68   = string(_b[gifted], "%4.2f")
    local se_m68  = string(_se[gifted], "%4.2f")
    local N_m68   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_m68 = "**"
    else if `p' < 0.05 local sig_m68 = "*"
    else if `p' < 0.10 local sig_m68 = "+"
    else                local sig_m68 = ""

    * ----- Column 2: No suspensions in MS -----
    xi: ivreg no_susp_ms (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_nosusp   = string(_b[gifted], "%4.2f")
    local se_nosusp  = string(_se[gifted], "%4.2f")
    local N_nosusp   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_nosusp = "**"
    else if `p' < 0.05 local sig_nosusp = "*"
    else if `p' < 0.10 local sig_nosusp = "+"
    else                local sig_nosusp = ""

    * ----- Column 3: HS math GPA -----
    xi: ivreg math_gpa_hs (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_mhs   = string(_b[gifted], "%4.2f")
    local se_mhs  = string(_se[gifted], "%4.2f")
    local N_mhs   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_mhs = "**"
    else if `p' < 0.05 local sig_mhs = "*"
    else if `p' < 0.10 local sig_mhs = "+"
    else                local sig_mhs = ""

    * ----- Column 4: HS language arts GPA -----
    xi: ivreg lang_arts_gpa_hs (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_lahs   = string(_b[gifted], "%4.2f")
    local se_lahs  = string(_se[gifted], "%4.2f")
    local N_lahs   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_lahs = "**"
    else if `p' < 0.05 local sig_lahs = "*"
    else if `p' < 0.10 local sig_lahs = "+"
    else                local sig_lahs = ""

    * ----- Column 5: Overall HS GPA -----
    xi: ivreg gpa_hs (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_gpa   = string(_b[gifted], "%4.2f")
    local se_gpa  = string(_se[gifted], "%4.2f")
    local N_gpa   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_gpa = "**"
    else if `p' < 0.05 local sig_gpa = "*"
    else if `p' < 0.10 local sig_gpa = "+"
    else                local sig_gpa = ""

    * ----- Coefficient row -----
    file write table "BW `bw'" "," ///
        `"`b_m68'`sig_m68'"' "," ///
        `"`b_nosusp'`sig_nosusp'"' "," ///
        `"`b_mhs'`sig_mhs'"' "," ///
        `"`b_lahs'`sig_lahs'"' "," ///
        `"`b_gpa'`sig_gpa'"' _n

    * ----- SE row -----
    file write table "," ///
        "(" `"`se_m68'"' ")" "," ///
        "(" `"`se_nosusp'"' ")" "," ///
        "(" `"`se_mhs'"' ")" "," ///
        "(" `"`se_lahs'"' ")" "," ///
        "(" `"`se_gpa'"' ")" _n

    * ----- Obs row -----
    file write table "Obs." "," ///
        "`N_m68'" "," ///
        "`N_nosusp'" "," ///
        "`N_mhs'" "," ///
        "`N_lahs'" "," ///
        "`N_gpa'" _n

    * Blank row between bandwidths
    file write table "," "," "," "," "," _n
}

********************************************************************************
* Panel B: Girls
********************************************************************************

file write table "Panel B. Girls Only" _n

foreach bw in 8 6 10 {

    * ----- Column 1: Math GPA, Grades 6-8 -----
    xi: ivreg math_gpa_g68 (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_m68   = string(_b[gifted], "%4.2f")
    local se_m68  = string(_se[gifted], "%4.2f")
    local N_m68   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_m68 = "**"
    else if `p' < 0.05 local sig_m68 = "*"
    else if `p' < 0.10 local sig_m68 = "+"
    else                local sig_m68 = ""

    * ----- Column 2: No suspensions in MS -----
    xi: ivreg no_susp_ms (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_nosusp   = string(_b[gifted], "%4.2f")
    local se_nosusp  = string(_se[gifted], "%4.2f")
    local N_nosusp   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_nosusp = "**"
    else if `p' < 0.05 local sig_nosusp = "*"
    else if `p' < 0.10 local sig_nosusp = "+"
    else                local sig_nosusp = ""

    * ----- Column 3: HS math GPA -----
    xi: ivreg math_gpa_hs (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_mhs   = string(_b[gifted], "%4.2f")
    local se_mhs  = string(_se[gifted], "%4.2f")
    local N_mhs   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_mhs = "**"
    else if `p' < 0.05 local sig_mhs = "*"
    else if `p' < 0.10 local sig_mhs = "+"
    else                local sig_mhs = ""

    * ----- Column 4: HS language arts GPA -----
    xi: ivreg lang_arts_gpa_hs (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_lahs   = string(_b[gifted], "%4.2f")
    local se_lahs  = string(_se[gifted], "%4.2f")
    local N_lahs   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_lahs = "**"
    else if `p' < 0.05 local sig_lahs = "*"
    else if `p' < 0.10 local sig_lahs = "+"
    else                local sig_lahs = ""

    * ----- Column 5: Overall HS GPA -----
    xi: ivreg gpa_hs (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_gpa   = string(_b[gifted], "%4.2f")
    local se_gpa  = string(_se[gifted], "%4.2f")
    local N_gpa   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_gpa = "**"
    else if `p' < 0.05 local sig_gpa = "*"
    else if `p' < 0.10 local sig_gpa = "+"
    else                local sig_gpa = ""

    * ----- Coefficient row -----
    file write table "BW `bw'" "," ///
        `"`b_m68'`sig_m68'"' "," ///
        `"`b_nosusp'`sig_nosusp'"' "," ///
        `"`b_mhs'`sig_mhs'"' "," ///
        `"`b_lahs'`sig_lahs'"' "," ///
        `"`b_gpa'`sig_gpa'"' _n

    * ----- SE row -----
    file write table "," ///
        "(" `"`se_m68'"' ")" "," ///
        "(" `"`se_nosusp'"' ")" "," ///
        "(" `"`se_mhs'"' ")" "," ///
        "(" `"`se_lahs'"' ")" "," ///
        "(" `"`se_gpa'"' ")" _n

    * ----- Obs row -----
    file write table "Obs." "," ///
        "`N_m68'" "," ///
        "`N_nosusp'" "," ///
        "`N_mhs'" "," ///
        "`N_lahs'" "," ///
        "`N_gpa'" _n

    * Blank row between bandwidths
    file write table "," "," "," "," "," _n
}

file close table

display ""
display "Table 4 created: $out\table_4_formatted.csv"
display ""

********************************************************************************
*** TABLE 5 - Peers (no Has Grade 6 Survey column)
********************************************************************************

* Assumes:
*   global donut
*   global bw6 bw8 bw10
* are already defined as in earlier tables.

file close _all
file open table using "$out\table_5_formatted.csv", write replace

* Header row: (1)-(7)
file write table "," "(1)" "," "(2)" "," "(3)" "," "(4)" "," "(5)" "," "(6)" "," "(7)" _n

* Header row: labels
file write table "," ///
    "Grade 6 Survey" "," ///
    "G6-G8: Peers All" "," ///
    "G6-G8: Peers Math Courses" "," ///
    "G6-G8: Peers Lang Arts Courses" "," ///
    "HS Peers: Peers All" "," ///
    "HS Peers: Math Courses" "," ///
    "HS Peers: Reading Courses" _n

********************************************************************************
* Panel A: Boys
********************************************************************************

file write table "Panel A. Boys Only" _n

foreach bw in 8 6 10 {

    * ----- (1) Grade 6 survey -----
    xi: ivreg g6svy (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_g6svy   = string(_b[gifted], "%4.2f")
    local se_g6svy  = string(_se[gifted], "%4.2f")
    local N_g6svy   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_g6svy = "**"
    else if `p' < 0.05 local sig_g6svy = "*"
    else if `p' < 0.10 local sig_g6svy = "+"
    else                local sig_g6svy = ""

    * ----- (2) G6-G8 Peers -----
    xi: ivreg peer_g35fcat_g68 (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_ms_any   = string(_b[gifted], "%4.2f")
    local se_ms_any  = string(_se[gifted], "%4.2f")
    local N_ms_any   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_ms_any = "**"
    else if `p' < 0.05 local sig_ms_any = "*"
    else if `p' < 0.10 local sig_ms_any = "+"
    else                local sig_ms_any = ""

    * ----- (3) G6-G8 peers: math -----
    xi: ivreg peer_g35fcat_g68_math (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_ms_math   = string(_b[gifted], "%4.2f")
    local se_ms_math  = string(_se[gifted], "%4.2f")
    local N_ms_math   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_ms_math = "**"
    else if `p' < 0.05 local sig_ms_math = "*"
    else if `p' < 0.10 local sig_ms_math = "+"
    else                local sig_ms_math = ""

    * ----- (4) G6-G8 peers: language arts -----
    xi: ivreg peer_g35fcat_g68_lang (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_ms_lang   = string(_b[gifted], "%4.2f")
    local se_ms_lang  = string(_se[gifted], "%4.2f")
    local N_ms_lang   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_ms_lang = "**"
    else if `p' < 0.05 local sig_ms_lang = "*"
    else if `p' < 0.10 local sig_ms_lang = "+"
    else                local sig_ms_lang = ""

    * ----- (5) HS peers: all -----
    xi: ivreg peer_g35fcat_hs (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_hs_any   = string(_b[gifted], "%4.2f")
    local se_hs_any  = string(_se[gifted], "%4.2f")
    local N_hs_any   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_hs_any = "**"
    else if `p' < 0.05 local sig_hs_any = "*"
    else if `p' < 0.10 local sig_hs_any = "+"
    else                local sig_hs_any = ""

    * ----- (6) HS peers: math -----
    xi: ivreg peer_g35fcat_hs_math (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_hs_math   = string(_b[gifted], "%4.2f")
    local se_hs_math  = string(_se[gifted], "%4.2f")
    local N_hs_math   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_hs_math = "**"
    else if `p' < 0.05 local sig_hs_math = "*"
    else if `p' < 0.10 local sig_hs_math = "+"
    else                local sig_hs_math = ""

    * ----- (7) HS peers: language arts -----
    xi: ivreg peer_g35fcat_hs_lang (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_hs_lang   = string(_b[gifted], "%4.2f")
    local se_hs_lang  = string(_se[gifted], "%4.2f")
    local N_hs_lang   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_hs_lang = "**"
    else if `p' < 0.05 local sig_hs_lang = "*"
    else if `p' < 0.10 local sig_hs_lang = "+"
    else                local sig_hs_lang = ""

    * ----- Coefficient row -----
    file write table "BW `bw'" "," ///
        `"`b_g6svy'`sig_g6svy'"' "," ///
        `"`b_ms_any'`sig_ms_any'"' "," ///
        `"`b_ms_math'`sig_ms_math'"' "," ///
        `"`b_ms_lang'`sig_ms_lang'"' "," ///
        `"`b_hs_any'`sig_hs_any'"' "," ///
        `"`b_hs_math'`sig_hs_math'"' "," ///
        `"`b_hs_lang'`sig_hs_lang'"' _n

    * ----- SE row -----
    file write table "," ///
        "(" `"`se_g6svy'"' ")" "," ///
        "(" `"`se_ms_any'"' ")" "," ///
        "(" `"`se_ms_math'"' ")" "," ///
        "(" `"`se_ms_lang'"' ")" "," ///
        "(" `"`se_hs_any'"' ")" "," ///
        "(" `"`se_hs_math'"' ")" "," ///
        "(" `"`se_hs_lang'"' ")" _n

    * ----- Obs row -----
    file write table "Obs." "," ///
        "`N_g6svy'" "," ///
        "`N_ms_any'" "," ///
        "`N_ms_math'" "," ///
        "`N_ms_lang'" "," ///
        "`N_hs_any'" "," ///
        "`N_hs_math'" "," ///
        "`N_hs_lang'" _n

    * Blank row between bandwidths
    file write table "," "," "," "," "," "," "," _n
}

********************************************************************************
* Panel B: Girls
********************************************************************************

file write table "Panel B. Girls Only" _n

foreach bw in 8 6 10 {

    * ----- (1) Grade 6 survey -----
    xi: ivreg g6svy (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_g6svy   = string(_b[gifted], "%4.2f")
    local se_g6svy  = string(_se[gifted], "%4.2f")
    local N_g6svy   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_g6svy = "**"
    else if `p' < 0.05 local sig_g6svy = "*"
    else if `p' < 0.10 local sig_g6svy = "+"
    else                local sig_g6svy = ""

    * ----- (2) G6-G8 peers: -----
    xi: ivreg peer_g35fcat_g68 (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_ms_any   = string(_b[gifted], "%4.2f")
    local se_ms_any  = string(_se[gifted], "%4.2f")
    local N_ms_any   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_ms_any = "**"
    else if `p' < 0.05 local sig_ms_any = "*"
    else if `p' < 0.10 local sig_ms_any = "+"
    else                local sig_ms_any = ""

    * ----- (3) G6-G8 peers: math -----
    xi: ivreg peer_g35fcat_g68_math (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_ms_math   = string(_b[gifted], "%4.2f")
    local se_ms_math  = string(_se[gifted], "%4.2f")
    local N_ms_math   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_ms_math = "**"
    else if `p' < 0.05 local sig_ms_math = "*"
    else if `p' < 0.10 local sig_ms_math = "+"
    else                local sig_ms_math = ""

    * ----- (4) G6-G8 peers: language arts -----
    xi: ivreg peer_g35fcat_g68_lang (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_ms_lang   = string(_b[gifted], "%4.2f")
    local se_ms_lang  = string(_se[gifted], "%4.2f")
    local N_ms_lang   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_ms_lang = "**"
    else if `p' < 0.05 local sig_ms_lang = "*"
    else if `p' < 0.10 local sig_ms_lang = "+"
    else                local sig_ms_lang = ""

    * ----- (5) HS peers: all -----
    xi: ivreg peer_g35fcat_hs (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_hs_any   = string(_b[gifted], "%4.2f")
    local se_hs_any  = string(_se[gifted], "%4.2f")
    local N_hs_any   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_hs_any = "**"
    else if `p' < 0.05 local sig_hs_any = "*"
    else if `p' < 0.10 local sig_hs_any = "+"
    else                local sig_hs_any = ""

    * ----- (6) HS peers: math -----
    xi: ivreg peer_g35fcat_hs_math (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_hs_math   = string(_b[gifted], "%4.2f")
    local se_hs_math  = string(_se[gifted], "%4.2f")
    local N_hs_math   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_hs_math = "**"
    else if `p' < 0.05 local sig_hs_math = "*"
    else if `p' < 0.10 local sig_hs_math = "+"
    else                local sig_hs_math = ""

    * ----- (7) HS peers: language arts -----
    xi: ivreg peer_g35fcat_hs_lang (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_hs_lang   = string(_b[gifted], "%4.2f")
    local se_hs_lang  = string(_se[gifted], "%4.2f")
    local N_hs_lang   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_hs_lang = "**"
    else if `p' < 0.05 local sig_hs_lang = "*"
    else if `p' < 0.10 local sig_hs_lang = "+"
    else                local sig_hs_lang = ""

    * ----- Coefficient row -----
    file write table "BW `bw'" "," ///
        `"`b_g6svy'`sig_g6svy'"' "," ///
        `"`b_ms_any'`sig_ms_any'"' "," ///
        `"`b_ms_math'`sig_ms_math'"' "," ///
        `"`b_ms_lang'`sig_ms_lang'"' "," ///
        `"`b_hs_any'`sig_hs_any'"' "," ///
        `"`b_hs_math'`sig_hs_math'"' "," ///
        `"`b_hs_lang'`sig_hs_lang'"' _n

    * ----- SE row -----
    file write table "," ///
        "(" `"`se_g6svy'"' ")" "," ///
        "(" `"`se_ms_any'"' ")" "," ///
        "(" `"`se_ms_math'"' ")" "," ///
        "(" `"`se_ms_lang'"' ")" "," ///
        "(" `"`se_hs_any'"' ")" "," ///
        "(" `"`se_hs_math'"' ")" "," ///
        "(" `"`se_hs_lang'"' ")" _n

    * ----- Obs row -----
    file write table "Obs." "," ///
        "`N_g6svy'" "," ///
        "`N_ms_any'" "," ///
        "`N_ms_math'" "," ///
        "`N_ms_lang'" "," ///
        "`N_hs_any'" "," ///
        "`N_hs_math'" "," ///
        "`N_hs_lang'" _n

    * Blank row
    file write table "," "," "," "," "," "," "," _n
}

file close table
display ""
display "Table 5 created: $out\table_5_formatted.csv"
display ""


********************************************************************************
*** TABLE 6 - Test scores
********************************************************************************

* Assumes:
*   global donut
*   global bw6 bw8 bw10
* are already defined as in earlier tables.

file close _all
file open table using "$out\table_6_formatted.csv", write replace

* Header row: (1)-(4)
file write table "," "(1)" "," "(2)" "," "(3)" "," "(4)" _n

* Header row: labels
file write table "," ///
    "Math, Grades 6-8" "," ///
    "Reading, Grades 6-8" "," ///
    "PSAT Math Percentile" "," ///
    "PSAT Reading Percentile" _n

********************************************************************************
* Panel A: Boys
********************************************************************************

file write table "Panel A. Boys Only" _n

foreach bw in 8 6 10 {

    * ----- (1) Math, Grades 6-8 -----
    xi: ivreg fcat678_math (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_fmath   = string(_b[gifted], "%4.2f")
    local se_fmath  = string(_se[gifted], "%4.2f")
    local N_fmath   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_fmath = "**"
    else if `p' < 0.05 local sig_fmath = "*"
    else if `p' < 0.10 local sig_fmath = "+"
    else                local sig_fmath = ""

    * ----- (2) Reading, Grades 6-8 -----
    xi: ivreg fcat678_read (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_fread   = string(_b[gifted], "%4.2f")
    local se_fread  = string(_se[gifted], "%4.2f")
    local N_fread   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_fread = "**"
    else if `p' < 0.05 local sig_fread = "*"
    else if `p' < 0.10 local sig_fread = "+"
    else                local sig_fread = ""

    * ----- (3) PSAT Math percentile -----
    xi: ivreg maxpsatmathpct (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_psatm   = string(_b[gifted], "%4.2f")
    local se_psatm  = string(_se[gifted], "%4.2f")
    local N_psatm   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_psatm = "**"
    else if `p' < 0.05 local sig_psatm = "*"
    else if `p' < 0.10 local sig_psatm = "+"
    else                local sig_psatm = ""

    * ----- (4) PSAT Reading percentile -----
    xi: ivreg maxpsatreadpct (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_psatr   = string(_b[gifted], "%4.2f")
    local se_psatr  = string(_se[gifted], "%4.2f")
    local N_psatr   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_psatr = "**"
    else if `p' < 0.05 local sig_psatr = "*"
    else if `p' < 0.10 local sig_psatr = "+"
    else                local sig_psatr = ""

    * ----- Coefficient row -----
    file write table "BW `bw'" "," ///
        `"`b_fmath'`sig_fmath'"' "," ///
        `"`b_fread'`sig_fread'"' "," ///
        `"`b_psatm'`sig_psatm'"' "," ///
        `"`b_psatr'`sig_psatr'"' _n

    * ----- SE row -----
    file write table "," ///
        "(" `"`se_fmath'"' ")" "," ///
        "(" `"`se_fread'"' ")" "," ///
        "(" `"`se_psatm'"' ")" "," ///
        "(" `"`se_psatr'"' ")" _n

    * ----- Obs row -----
    file write table "Obs." "," ///
        "`N_fmath'" "," ///
        "`N_fread'" "," ///
        "`N_psatm'" "," ///
        "`N_psatr'" _n

    * Blank row between bandwidths
    file write table "," "," "," "," _n
}

********************************************************************************
* Panel B: Girls
********************************************************************************

file write table "Panel B. Girls Only" _n

foreach bw in 8 6 10 {

    * ----- (1) Math, Grades 6-8 -----
    xi: ivreg fcat678_math (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_fmath   = string(_b[gifted], "%4.2f")
    local se_fmath  = string(_se[gifted], "%4.2f")
    local N_fmath   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_fmath = "**"
    else if `p' < 0.05 local sig_fmath = "*"
    else if `p' < 0.10 local sig_fmath = "+"
    else                local sig_fmath = ""

    * ----- (2) Reading, Grades 6-8 -----
    xi: ivreg fcat678_read (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_fread   = string(_b[gifted], "%4.2f")
    local se_fread  = string(_se[gifted], "%4.2f")
    local N_fread   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_fread = "**"
    else if `p' < 0.05 local sig_fread = "*"
    else if `p' < 0.10 local sig_fread = "+"
    else                local sig_fread = ""

    * ----- (3) Max PSAT Math percentile -----
    xi: ivreg maxpsatmathpct (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_psatm   = string(_b[gifted], "%4.2f")
    local se_psatm  = string(_se[gifted], "%4.2f")
    local N_psatm   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_psatm = "**"
    else if `p' < 0.05 local sig_psatm = "*"
    else if `p' < 0.10 local sig_psatm = "+"
    else                local sig_psatm = ""

    * ----- (4) Max PSAT Reading percentile -----
    xi: ivreg maxpsatreadpct (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_psatr   = string(_b[gifted], "%4.2f")
    local se_psatr  = string(_se[gifted], "%4.2f")
    local N_psatr   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_psatr = "**"
    else if `p' < 0.05 local sig_psatr = "*"
    else if `p' < 0.10 local sig_psatr = "+"
    else                local sig_psatr = ""

    * ----- Coefficient row -----
    file write table "BW `bw'" "," ///
        `"`b_fmath'`sig_fmath'"' "," ///
        `"`b_fread'`sig_fread'"' "," ///
        `"`b_psatm'`sig_psatm'"' "," ///
        `"`b_psatr'`sig_psatr'"' _n

    * ----- SE row -----
    file write table "," ///
        "(" `"`se_fmath'"' ")" "," ///
        "(" `"`se_fread'"' ")" "," ///
        "(" `"`se_psatm'"' ")" "," ///
        "(" `"`se_psatr'"' ")" _n

    * ----- Obs row -----
    file write table "Obs." "," ///
        "`N_fmath'" "," ///
        "`N_fread'" "," ///
        "`N_psatm'" "," ///
        "`N_psatr'" _n

    * Blank row between bandwidths
    file write table "," "," "," "," _n
}

file close table

display ""
display "Table 6 created: $out\table_6_formatted.csv"
display ""


********************************************************************************
*** APPENDIX TABLE C1 - Role of Participation in Gifted/High Achiever Classroom
********************************************************************************

* Assumes:
*   global donut
*   global bw8
*   and variables: gha, collot, gifted, r, d, dxr, m, f, schid

file close _all
file open table using "$out\table_C1_formatted.csv", write replace

* Row 1: column numbers
file write table "," "(1)" "," "(2)" "," "(3)" "," "(4)" "," "(5)" "," "(6)" _n

* Row 2: broad group headers
file write table "," ///
    "GHA Classroom Participation" "," ///
    "GHA Classroom Participation" "," ///
    "GHA Classroom Participation" "," ///
    "On-Time College Enrollment" "," ///
    "On-Time College Enrollment" "," ///
    "On-Time College Enrollment" _n

* Row 3: detailed column labels
file write table "," ///
    "Pooled" "," ///
    "Fewer Non-Gifted Seats in GHA Classroom" "," ///
    "More Non-Gifted Seats in GHA Classroom" "," ///
    "Pooled" "," ///
    "Fewer Non-Gifted Seats in GHA Classroom" "," ///
    "More Non-Gifted Seats in GHA Classroom" _n

********************************************************************************
* Panel A: Boys
********************************************************************************

file write table "Panel A. Boys Only" _n

* ----- Boys, BW 8 -----

* (1) GHA participation - pooled (hipctgft ~= .)
xi: ivreg gha (gifted = r d dxr) r dxr ///
    if $donut & ${bw8} & m==1 & hipctgft < . , cluster(schid)
local b_gha_pool   = string(_b[gifted], "%4.2f")
local se_gha_pool  = string(_se[gifted], "%4.2f")
local N_gha_pool   = e(N)
test gifted
local p = r(p)
if      `p' < 0.01 local sig_gha_pool = "**"
else if `p' < 0.05 local sig_gha_pool = "*"
else if `p' < 0.10 local sig_gha_pool = "+"
else                local sig_gha_pool = ""

* (2) GHA participation - high non-gifted seats (hipctgft==1)
xi: ivreg gha (gifted = r d dxr) r dxr ///
    if $donut & ${bw8} & m==1 & hipctgft == 1, cluster(schid)
local b_gha_hi   = string(_b[gifted], "%4.2f")
local se_gha_hi  = string(_se[gifted], "%4.2f")
local N_gha_hi   = e(N)
test gifted
local p = r(p)
if      `p' < 0.01 local sig_gha_hi = "**"
else if `p' < 0.05 local sig_gha_hi = "*"
else if `p' < 0.10 local sig_gha_hi = "+"
else                local sig_gha_hi = ""

* (3) GHA participation - low non-gifted seats (hipctgft==0)
xi: ivreg gha (gifted = r d dxr) r dxr ///
    if $donut & ${bw8} & m==1 & hipctgft == 0, cluster(schid)
local b_gha_lo   = string(_b[gifted], "%4.2f")
local se_gha_lo  = string(_se[gifted], "%4.2f")
local N_gha_lo   = e(N)
test gifted
local p = r(p)
if      `p' < 0.01 local sig_gha_lo = "**"
else if `p' < 0.05 local sig_gha_lo = "*"
else if `p' < 0.10 local sig_gha_lo = "+"
else                local sig_gha_lo = ""

* (4) On-time college - pooled
xi: ivreg collot (gifted = r d dxr) r dxr ///
    if $donut & ${bw8} & m==1 & hipctgft < . , cluster(schid)
local b_coll_pool   = string(_b[gifted], "%4.2f")
local se_coll_pool  = string(_se[gifted], "%4.2f")
local N_coll_pool   = e(N)
test gifted
local p = r(p)
if      `p' < 0.01 local sig_coll_pool = "**"
else if `p' < 0.05 local sig_coll_pool = "*"
else if `p' < 0.10 local sig_coll_pool = "+"
else                local sig_coll_pool = ""

* (5) On-time college - high non-gifted seats
xi: ivreg collot (gifted = r d dxr) r dxr ///
    if $donut & ${bw8} & m==1 & hipctgft == 1, cluster(schid)
local b_coll_hi   = string(_b[gifted], "%4.2f")
local se_coll_hi  = string(_se[gifted], "%4.2f")
local N_coll_hi   = e(N)
test gifted
local p = r(p)
if      `p' < 0.01 local sig_coll_hi = "**"
else if `p' < 0.05 local sig_coll_hi = "*"
else if `p' < 0.10 local sig_coll_hi = "+"
else                local sig_coll_hi = ""

* (6) On-time college - low non-gifted seats
xi: ivreg collot (gifted = r d dxr) r dxr ///
    if $donut & ${bw8} & m==1 & hipctgft == 0, cluster(schid)
local b_coll_lo   = string(_b[gifted], "%4.2f")
local se_coll_lo  = string(_se[gifted], "%4.2f")
local N_coll_lo   = e(N)
test gifted
local p = r(p)
if      `p' < 0.01 local sig_coll_lo = "**"
else if `p' < 0.05 local sig_coll_lo = "*"
else if `p' < 0.10 local sig_coll_lo = "+"
else                local sig_coll_lo = ""

* ---- Boys rows: coefficients, SEs, obs ----

file write table "BW 8" "," ///
    `"`b_gha_pool'`sig_gha_pool'"' "," ///
    `"`b_gha_hi'`sig_gha_hi'"' "," ///
    `"`b_gha_lo'`sig_gha_lo'"' "," ///
    `"`b_coll_pool'`sig_coll_pool'"' "," ///
    `"`b_coll_hi'`sig_coll_hi'"' "," ///
    `"`b_coll_lo'`sig_coll_lo'"' _n

file write table "," ///
    "(" `"`se_gha_pool'"' ")" "," ///
    "(" `"`se_gha_hi'"' ")" "," ///
    "(" `"`se_gha_lo'"' ")" "," ///
    "(" `"`se_coll_pool'"' ")" "," ///
    "(" `"`se_coll_hi'"' ")" "," ///
    "(" `"`se_coll_lo'"' ")" _n

file write table "Obs." "," ///
    "`N_gha_pool'" "," ///
    "`N_gha_hi'" "," ///
    "`N_gha_lo'" "," ///
    "`N_coll_pool'" "," ///
    "`N_coll_hi'" "," ///
    "`N_coll_lo'" _n

file write table "," "," "," "," "," "," _n

********************************************************************************
* Panel B: Girls
********************************************************************************

file write table "Panel B. Girls Only" _n

* (1) GHA participation - pooled
xi: ivreg gha (gifted = r d dxr) r dxr ///
    if $donut & ${bw8} & f==1 & hipctgft < . , cluster(schid)
local b_gha_pool   = string(_b[gifted], "%4.2f")
local se_gha_pool  = string(_se[gifted], "%4.2f")
local N_gha_pool   = e(N)
test gifted
local p = r(p)
if      `p' < 0.01 local sig_gha_pool = "**"
else if `p' < 0.05 local sig_gha_pool = "*"
else if `p' < 0.10 local sig_gha_pool = "+"
else                local sig_gha_pool = ""

* (2) GHA participation - high non-gifted seats
xi: ivreg gha (gifted = r d dxr) r dxr ///
    if $donut & ${bw8} & f==1 & hipctgft == 1, cluster(schid)
local b_gha_hi   = string(_b[gifted], "%4.2f")
local se_gha_hi  = string(_se[gifted], "%4.2f")
local N_gha_hi   = e(N)
test gifted
local p = r(p)
if      `p' < 0.01 local sig_gha_hi = "**"
else if `p' < 0.05 local sig_gha_hi = "*"
else if `p' < 0.10 local sig_gha_hi = "+"
else                local sig_gha_hi = ""

* (3) GHA participation - low non-gifted seats
xi: ivreg gha (gifted = r d dxr) r dxr ///
    if $donut & ${bw8} & f==1 & hipctgft == 0, cluster(schid)
local b_gha_lo   = string(_b[gifted], "%4.2f")
local se_gha_lo  = string(_se[gifted], "%4.2f")
local N_gha_lo   = e(N)
test gifted
local p = r(p)
if      `p' < 0.01 local sig_gha_lo = "**"
else if `p' < 0.05 local sig_gha_lo = "*"
else if `p' < 0.10 local sig_gha_lo = "+"
else                local sig_gha_lo = ""

* (4) On-time college - pooled
xi: ivreg collot (gifted = r d dxr) r dxr ///
    if $donut & ${bw8} & f==1 & hipctgft < . , cluster(schid)
local b_coll_pool   = string(_b[gifted], "%4.2f")
local se_coll_pool  = string(_se[gifted], "%4.2f")
local N_coll_pool   = e(N)
test gifted
local p = r(p)
if      `p' < 0.01 local sig_coll_pool = "**"
else if `p' < 0.05 local sig_coll_pool = "*"
else if `p' < 0.10 local sig_coll_pool = "+"
else                local sig_coll_pool = ""

* (5) On-time college - high non-gifted seats
xi: ivreg collot (gifted = r d dxr) r dxr ///
    if $donut & ${bw8} & f==1 & hipctgft == 1, cluster(schid)
local b_coll_hi   = string(_b[gifted], "%4.2f")
local se_coll_hi  = string(_se[gifted], "%4.2f")
local N_coll_hi   = e(N)
test gifted
local p = r(p)
if      `p' < 0.01 local sig_coll_hi = "**"
else if `p' < 0.05 local sig_coll_hi = "*"
else if `p' < 0.10 local sig_coll_hi = "+"
else                local sig_coll_hi = ""

* (6) On-time college - low non-gifted seats
xi: ivreg collot (gifted = r d dxr) r dxr ///
    if $donut & ${bw8} & f==1 & hipctgft == 0, cluster(schid)
local b_coll_lo   = string(_b[gifted], "%4.2f")
local se_coll_lo  = string(_se[gifted], "%4.2f")
local N_coll_lo   = e(N)
test gifted
local p = r(p)
if      `p' < 0.01 local sig_coll_lo = "**"
else if `p' < 0.05 local sig_coll_lo = "*"
else if `p' < 0.10 local sig_coll_lo = "+"
else                local sig_coll_lo = ""

* ---- Girls rows: coefficients, SEs, obs ----

file write table "BW 8" "," ///
    `"`b_gha_pool'`sig_gha_pool'"' "," ///
    `"`b_gha_hi'`sig_gha_hi'"' "," ///
    `"`b_gha_lo'`sig_gha_lo'"' "," ///
    `"`b_coll_pool'`sig_coll_pool'"' "," ///
    `"`b_coll_hi'`sig_coll_hi'"' "," ///
    `"`b_coll_lo'`sig_coll_lo'"' _n

file write table "," ///
    "(" `"`se_gha_pool'"' ")" "," ///
    "(" `"`se_gha_hi'"' ")" "," ///
    "(" `"`se_gha_lo'"' ")" "," ///
    "(" `"`se_coll_pool'"' ")" "," ///
    "(" `"`se_coll_hi'"' ")" "," ///
    "(" `"`se_coll_lo'"' ")" _n

file write table "Obs." "," ///
    "`N_gha_pool'" "," ///
    "`N_gha_hi'" "," ///
    "`N_gha_lo'" "," ///
    "`N_coll_pool'" "," ///
    "`N_coll_hi'" "," ///
    "`N_coll_lo'" _n

file close table
display ""
display "Appendix Table C1 created: $out\table_C1_formatted.csv"
display ""


********************************************************************************
*** APPENDIX TABLE A3 - Student Characteristics, Plan B vs Non-Gifted Compliers
********************************************************************************

gen notgifted = (1-gifted)

* Characteristic variables (same order as paper)
global char ///
    gha gem6 peer_g35fcat_g68_math peer_g35fcat_g68_lang alg8 no_susp_ms ///
    peer_g35fcat_hs_lang peer_g35fcat_hs_lang math_gpa_hs lang_arts_gpa_hs gpa_hs ///
    num_ap_course fcat678_avgany fcat678_math fcat678_read ///
    maxpsattotpct maxpsatmathpct maxpsatreadpct collot

* Ensure pooled indicator exists
cap confirm variable all
if _rc {
    gen all = (m==1 | f==1)
}

* Interactions for complier means (D*Y)
foreach var of varlist $char {
    cap drop notgifted_x_`var'
    gen notgifted_x_`var' = notgifted*`var'
}

file close _all
file open table using "$out\table_A3_formatted.csv", write replace

* ----------------------------------------------------------------------
* Header rows
* ----------------------------------------------------------------------

* Column numbers
file write table "," "(1)" "," "(2)" "," "(3)" "," "(4)" "," "(5)" _n

* Group headers
file write table "," ///
    "Plan B + IQ Scores 106-124" "," ///
    "Plan B + IQ Scores 106-124" "," ///
    "Plan B + IQ Scores 106-124" "," ///
    "Non-Gifted Compliers" "," ///
    "Non-Gifted Compliers" _n

* Subheaders
file write table "," ///
    "Pooled" "," ///
    "Boys" "," ///
    "Girls" "," ///
    "Boys" "," ///
    "Girls" _n

* ----------------------------------------------------------------------
* Helper macro: compute means for one characteristic and write row
* ----------------------------------------------------------------------
cap program drop _a3_row
program define _a3_row, rclass
    syntax varname, Label(string)

    * Plan B means (pooled / boys / girls)
    quietly summarize `varlist' if $donut & ${bw8} & all==1
    local mean_all = r(mean)

    quietly summarize `varlist' if $donut & ${bw8} & m==1
    local mean_m = r(mean)

    quietly summarize `varlist' if $donut & ${bw8} & f==1
    local mean_f = r(mean)

    * Complier means (non-gifted compliers), boys
    quietly xi: ivreg notgifted_x_`varlist' ///
        (notgifted = r d dxr) r dxr ///
        if $donut & ${bw8} & m==1, cluster(schid)
    local comp_m = _b[notgifted]

    * Complier means, girls
    quietly xi: ivreg notgifted_x_`varlist' ///
        (notgifted = r d dxr) r dxr ///
        if $donut & ${bw8} & f==1, cluster(schid)
    local comp_f = _b[notgifted]

    * Format
    local b1 = string(`mean_all', "%4.2f")
    local b2 = string(`mean_m',   "%4.2f")
    local b3 = string(`mean_f',   "%4.2f")
    local b4 = string(`comp_m',   "%4.2f")
    local b5 = string(`comp_f',   "%4.2f")

    * Write row
    file write table `"`label'"' "," ///
        "`b1'" "," "`b2'" "," "`b3'" "," "`b4'" "," "`b5'" _n
end

* ----------------------------------------------------------------------
* Panel A: Non-Cognitive Outcomes
* ----------------------------------------------------------------------

file write table "Panel A. Non-Cognitive Outcomes" _n

_a3_row gha, ///
    label("Gifted/High-Achieving Classroom Enrollment")

_a3_row gem6, ///
    label("GEM Enrollment 6th Grade")

_a3_row peer_g35math_g68, ///
    label("G6-G8 Peers Math Courses (\sigma units)")

_a3_row peer_g35read_g68, ///
    label("G6-G8 Peers Reading Courses (\sigma units)")

_a3_row alg8, ///
    label("Algebra Enrollment by 8th Grade")

_a3_row no_susp_ms, ///
    label("G6-G8 No Suspensions")

_a3_row peer_g35math_hs, ///
    label("HS Peers Math Courses (\sigma units)")

_a3_row peer_g35read_hs, ///
    label("HS Peers Reading Courses (\sigma units)")

_a3_row math_gpa_hs, ///
    label("HS Math GPA")

_a3_row lang_arts_gpa_hs, ///
    label("HS Lang. Arts GPA")

_a3_row gpa_hs, ///
    label("HS GPA")

_a3_row num_ap_course, ///
    label("Number of AP Courses")

file write table "" _n

* ----------------------------------------------------------------------
* Panel B: Cognitive Outcomes
* ----------------------------------------------------------------------

file write table "Panel B. Cognitive Outcomes" _n

_a3_row fcat678_avgany, ///
    label("G6-G8 Test Scores (\sigma units)")

_a3_row fcat678_math, ///
    label("G6-G8 Math Test Scores (\sigma units)")

_a3_row fcat678_read, ///
    label("G6-G8 Reading Test Scores (\sigma units)")

_a3_row maxpsattotpct, ///
    label("PSAT (Percentile)")

_a3_row maxpsatmathpct, ///
    label("PSAT Math (Percentile)")

_a3_row maxpsatreadpct, ///
    label("PSAT Reading (Percentile)")

file write table "" _n

* ----------------------------------------------------------------------
* Panel C: College
* ----------------------------------------------------------------------

file write table "Panel C. College" _n

_a3_row collot, ///
    label("Grad HS On Time + Enroll Within 1 Yr.")

* ----------------------------------------------------------------------
* Observations row (base sample sizes)
* ----------------------------------------------------------------------

quietly count if $donut & ${bw8} & all==1
local N_all = r(N)

quietly count if $donut & ${bw8} & m==1
local N_m = r(N)

quietly count if $donut & ${bw8} & f==1
local N_f = r(N)

file write table "Observations" "," ///
    "`N_all'" "," "`N_m'" "," "`N_f'" "," ///
    "," _n

file close table
display ""
display "Appendix Table A3 created: $out\table_A3_formatted.csv"
display ""

********************************************************************************
*** APPENDIX TABLE A4 - Balance Analysis
********************************************************************************

* Balance variables
global more_balance ///
    age frl lep white black hispanic g3read g3math ///
    sch_nonwhite sch_frl sch_medhhy sch_zg5_mean

* Assumes:
*   global donut
*   global bw6 bw8 bw10
* defined earlier (as in other tables)

file close _all
file open table using "$out\table_A4_formatted.csv", write replace

* --------------------------------------------------
* Header rows
* --------------------------------------------------

* Column numbers (1-12)
file write table "," "(1)" "," "(2)" "," "(3)" "," "(4)" "," "(5)" "," "(6)" "," ///
                     "(7)" "," "(8)" "," "(9)" "," "(10)" "," "(11)" "," "(12)" _n

* Variable labels
file write table "," ///
    "Age" "," ///
    "FRL" "," ///
    "LEP" "," ///
    "White" "," ///
    "Black" "," ///
    "Hispanic" "," ///
    "G3 Reading Score" "," ///
    "G3 Math Score" "," ///
    "School \% Non-White" "," ///
    "School \% FRL" "," ///
    "School Median HH Income" "," ///
    "School G5 Z-Score Mean" _n

********************************************************************************
* Panel A: Boys
********************************************************************************

file write table "Panel A. Boys Only" _n

foreach bw in 8 6 10 {

    * ----- age -----
    xi: ivreg age r d dxr if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_age   = string(_b[d], "%4.2f")
    local se_age  = string(_se[d], "%4.2f")
    local N_age   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_age = "**"
    else if `p' < 0.05 local sig_age = "*"
    else if `p' < 0.10 local sig_age = "+"
    else                local sig_age = ""

    * ----- frl -----
    xi: ivreg frl r d dxr if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_frl   = string(_b[d], "%4.2f")
    local se_frl  = string(_se[d], "%4.2f")
    local N_frl   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_frl = "**"
    else if `p' < 0.05 local sig_frl = "*"
    else if `p' < 0.10 local sig_frl = "+"
    else                local sig_frl = ""

    * ----- lep -----
    xi: ivreg lep r d dxr if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_lep   = string(_b[d], "%4.2f")
    local se_lep  = string(_se[d], "%4.2f")
    local N_lep   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_lep = "**"
    else if `p' < 0.05 local sig_lep = "*"
    else if `p' < 0.10 local sig_lep = "+"
    else                local sig_lep = ""

    * ----- white -----
    xi: ivreg white r d dxr if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_white   = string(_b[d], "%4.2f")
    local se_white  = string(_se[d], "%4.2f")
    local N_white   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_white = "**"
    else if `p' < 0.05 local sig_white = "*"
    else if `p' < 0.10 local sig_white = "+"
    else                local sig_white = ""

    * ----- black -----
    xi: ivreg black r d dxr if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_black   = string(_b[d], "%4.2f")
    local se_black  = string(_se[d], "%4.2f")
    local N_black   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_black = "**"
    else if `p' < 0.05 local sig_black = "*"
    else if `p' < 0.10 local sig_black = "+"
    else                local sig_black = ""

    * ----- hispanic -----
    xi: ivreg hispanic r d dxr if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_hisp   = string(_b[d], "%4.2f")
    local se_hisp  = string(_se[d], "%4.2f")
    local N_hisp   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_hisp = "**"
    else if `p' < 0.05 local sig_hisp = "*"
    else if `p' < 0.10 local sig_hisp = "+"
    else                local sig_hisp = ""

    * ----- g3read -----
    xi: ivreg g3read r d dxr if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_g3r   = string(_b[d], "%4.2f")
    local se_g3r  = string(_se[d], "%4.2f")
    local N_g3r   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_g3r = "**"
    else if `p' < 0.05 local sig_g3r = "*"
    else if `p' < 0.10 local sig_g3r = "+"
    else                local sig_g3r = ""

    * ----- g3math -----
    xi: ivreg g3math r d dxr if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_g3m   = string(_b[d], "%4.2f")
    local se_g3m  = string(_se[d], "%4.2f")
    local N_g3m   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_g3m = "**"
    else if `p' < 0.05 local sig_g3m = "*"
    else if `p' < 0.10 local sig_g3m = "+"
    else                local sig_g3m = ""

    * ----- sch_nonwhite -----
    xi: ivreg sch_nonwhite r d dxr if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_snon   = string(_b[d], "%4.2f")
    local se_snon  = string(_se[d], "%4.2f")
    local N_snon   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_snon = "**"
    else if `p' < 0.05 local sig_snon = "*"
    else if `p' < 0.10 local sig_snon = "+"
    else                local sig_snon = ""

    * ----- sch_frl -----
    xi: ivreg sch_frl r d dxr if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_sfrl   = string(_b[d], "%4.2f")
    local se_sfrl  = string(_se[d], "%4.2f")
    local N_sfrl   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_sfrl = "**"
    else if `p' < 0.05 local sig_sfrl = "*"
    else if `p' < 0.10 local sig_sfrl = "+"
    else                local sig_sfrl = ""

    * ----- sch_medhhy -----
    xi: ivreg sch_medhhy r d dxr if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_smed   = string(_b[d], "%4.2f")
    local se_smed  = string(_se[d], "%4.2f")
    local N_smed   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_smed = "**"
    else if `p' < 0.05 local sig_smed = "*"
    else if `p' < 0.10 local sig_smed = "+"
    else                local sig_smed = ""

    * ----- sch_zg5_mean -----
    xi: ivreg sch_zg5_mean r d dxr if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_szg5   = string(_b[d], "%4.2f")
    local se_szg5  = string(_se[d], "%4.2f")
    local N_szg5   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_szg5 = "**"
    else if `p' < 0.05 local sig_szg5 = "*"
    else if `p' < 0.10 local sig_szg5 = "+"
    else                local sig_szg5 = ""

    * ----- Coefficient row for this BW -----
    file write table "BW `bw'" "," ///
        `"`b_age'`sig_age'"' "," ///
        `"`b_frl'`sig_frl'"' "," ///
        `"`b_lep'`sig_lep'"' "," ///
        `"`b_white'`sig_white'"' "," ///
        `"`b_black'`sig_black'"' "," ///
        `"`b_hisp'`sig_hisp'"' "," ///
        `"`b_g3r'`sig_g3r'"' "," ///
        `"`b_g3m'`sig_g3m'"' "," ///
        `"`b_snon'`sig_snon'"' "," ///
        `"`b_sfrl'`sig_sfrl'"' "," ///
        `"`b_smed'`sig_smed'"' "," ///
        `"`b_szg5'`sig_szg5'"' _n

    * ----- SE row -----
    file write table "," ///
        "(" `"`se_age'"' ")" "," ///
        "(" `"`se_frl'"' ")" "," ///
        "(" `"`se_lep'"' ")" "," ///
        "(" `"`se_white'"' ")" "," ///
        "(" `"`se_black'"' ")" "," ///
        "(" `"`se_hisp'"' ")" "," ///
        "(" `"`se_g3r'"' ")" "," ///
        "(" `"`se_g3m'"' ")" "," ///
        "(" `"`se_snon'"' ")" "," ///
        "(" `"`se_sfrl'"' ")" "," ///
        "(" `"`se_smed'"' ")" "," ///
        "(" `"`se_szg5'"' ")" _n

    * ----- Obs row -----
    file write table "Obs." "," ///
        "`N_age'" "," ///
        "`N_frl'" "," ///
        "`N_lep'" "," ///
        "`N_white'" "," ///
        "`N_black'" "," ///
        "`N_hisp'" "," ///
        "`N_g3r'" "," ///
        "`N_g3m'" "," ///
        "`N_snon'" "," ///
        "`N_sfrl'" "," ///
        "`N_smed'" "," ///
        "`N_szg5'" _n

    * Blank row
    file write table "," "," "," "," "," "," "," "," "," "," "," "," _n
}

********************************************************************************
* Panel B: Girls
********************************************************************************

file write table "Panel B. Girls Only" _n

foreach bw in 8 6 10 {

    * Repeat same structure but with f==1 instead of m==1

    xi: ivreg age r d dxr if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_age   = string(_b[d], "%4.2f")
    local se_age  = string(_se[d], "%4.2f")
    local N_age   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_age = "**"
    else if `p' < 0.05 local sig_age = "*"
    else if `p' < 0.10 local sig_age = "+"
    else                local sig_age = ""

    xi: ivreg frl r d dxr if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_frl   = string(_b[d], "%4.2f")
    local se_frl  = string(_se[d], "%4.2f")
    local N_frl   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_frl = "**"
    else if `p' < 0.05 local sig_frl = "*"
    else if `p' < 0.10 local sig_frl = "+"
    else                local sig_frl = ""

    xi: ivreg lep r d dxr if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_lep   = string(_b[d], "%4.2f")
    local se_lep  = string(_se[d], "%4.2f")
    local N_lep   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_lep = "**"
    else if `p' < 0.05 local sig_lep = "*"
    else if `p' < 0.10 local sig_lep = "+"
    else                local sig_lep = ""

    xi: ivreg white r d dxr if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_white   = string(_b[d], "%4.2f")
    local se_white  = string(_se[d], "%4.2f")
    local N_white   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_white = "**"
    else if `p' < 0.05 local sig_white = "*"
    else if `p' < 0.10 local sig_white = "+"
    else                local sig_white = ""

    xi: ivreg black r d dxr if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_black   = string(_b[d], "%4.2f")
    local se_black  = string(_se[d], "%4.2f")
    local N_black   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_black = "**"
    else if `p' < 0.05 local sig_black = "*"
    else if `p' < 0.10 local sig_black = "+"
    else                local sig_black = ""

    xi: ivreg hispanic r d dxr if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_hisp   = string(_b[d], "%4.2f")
    local se_hisp  = string(_se[d], "%4.2f")
    local N_hisp   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_hisp = "**"
    else if `p' < 0.05 local sig_hisp = "*"
    else if `p' < 0.10 local sig_hisp = "+"
    else                local sig_hisp = ""

    xi: ivreg g3read r d dxr if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_g3r   = string(_b[d], "%4.2f")
    local se_g3r  = string(_se[d], "%4.2f")
    local N_g3r   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_g3r = "**"
    else if `p' < 0.05 local sig_g3r = "*"
    else if `p' < 0.10 local sig_g3r = "+"
    else                local sig_g3r = ""

    xi: ivreg g3math r d dxr if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_g3m   = string(_b[d], "%4.2f")
    local se_g3m  = string(_se[d], "%4.2f")
    local N_g3m   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_g3m = "**"
    else if `p' < 0.05 local sig_g3m = "*"
    else if `p' < 0.10 local sig_g3m = "+"
    else                local sig_g3m = ""

    xi: ivreg sch_nonwhite r d dxr if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_snon   = string(_b[d], "%4.2f")
    local se_snon  = string(_se[d], "%4.2f")
    local N_snon   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_snon = "**"
    else if `p' < 0.05 local sig_snon = "*"
    else if `p' < 0.10 local sig_snon = "+"
    else                local sig_snon = ""

    xi: ivreg sch_frl r d dxr if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_sfrl   = string(_b[d], "%4.2f")
    local se_sfrl  = string(_se[d], "%4.2f")
    local N_sfrl   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_sfrl = "**"
    else if `p' < 0.05 local sig_sfrl = "*"
    else if `p' < 0.10 local sig_sfrl = "+"
    else                local sig_sfrl = ""

    xi: ivreg sch_medhhy r d dxr if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_smed   = string(_b[d], "%4.2f")
    local se_smed  = string(_se[d], "%4.2f")
    local N_smed   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_smed = "**"
    else if `p' < 0.05 local sig_smed = "*"
    else if `p' < 0.10 local sig_smed = "+"
    else                local sig_smed = ""

    xi: ivreg sch_zg5_mean r d dxr if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_szg5   = string(_b[d], "%4.2f")
    local se_szg5  = string(_se[d], "%4.2f")
    local N_szg5   = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_szg5 = "**"
    else if `p' < 0.05 local sig_szg5 = "*"
    else if `p' < 0.10 local sig_szg5 = "+"
    else                local sig_szg5 = ""

    file write table "BW `bw'" "," ///
        `"`b_age'`sig_age'"' "," ///
        `"`b_frl'`sig_frl'"' "," ///
        `"`b_lep'`sig_lep'"' "," ///
        `"`b_white'`sig_white'"' "," ///
        `"`b_black'`sig_black'"' "," ///
        `"`b_hisp'`sig_hisp'"' "," ///
        `"`b_g3r'`sig_g3r'"' "," ///
        `"`b_g3m'`sig_g3m'"' "," ///
        `"`b_snon'`sig_snon'"' "," ///
        `"`b_sfrl'`sig_sfrl'"' "," ///
        `"`b_smed'`sig_smed'"' "," ///
        `"`b_szg5'`sig_szg5'"' _n

    file write table "," ///
        "(" `"`se_age'"' ")" "," ///
        "(" `"`se_frl'"' ")" "," ///
        "(" `"`se_lep'"' ")" "," ///
        "(" `"`se_white'"' ")" "," ///
        "(" `"`se_black'"' ")" "," ///
        "(" `"`se_hisp'"' ")" "," ///
        "(" `"`se_g3r'"' ")" "," ///
        "(" `"`se_g3m'"' ")" "," ///
        "(" `"`se_snon'"' ")" "," ///
        "(" `"`se_sfrl'"' ")" "," ///
        "(" `"`se_smed'"' ")" "," ///
        "(" `"`se_szg5'"' ")" _n

    file write table "Obs." "," ///
        "`N_age'" "," ///
        "`N_frl'" "," ///
        "`N_lep'" "," ///
        "`N_white'" "," ///
        "`N_black'" "," ///
        "`N_hisp'" "," ///
        "`N_g3r'" "," ///
        "`N_g3m'" "," ///
        "`N_snon'" "," ///
        "`N_sfrl'" "," ///
        "`N_smed'" "," ///
        "`N_szg5'" _n

    file write table "," "," "," "," "," "," "," "," "," "," "," "," _n
}

file close table
display ""
display "Appendix Table A4 created: $out\table_A4_formatted.csv"
display ""

********************************************************************************
*** APPENDIX TABLE A8 - Alternative Measures of Graduation and College Enrollment
********************************************************************************

* Assumes:
*   global donut, bw6, bw8, bw10 defined earlier
*   indicator all exists (pooled sample)
*   treatment variable: gifted; instruments: r d dxr; cluster(schid)

file close _all
file open table using "$out\table_A8_formatted.csv", write replace

* ---------------------------------------------------------------------------
* Header rows
* ---------------------------------------------------------------------------

* Column numbers (1)-(6)
file write table "," "(1)" "," "(2)" "," "(3)" "," "(4)" "," "(5)" "," "(6)" _n

* Column labels
file write table "," ///
    "HS Graduation (On-Time or Late)" "," ///
    "HS Graduation (On-Time or Late, Plan B Sample)" "," ///
    "HS Graduation (On-Time, Plan B Sample)" "," ///
    "On-Time College Enrollment (Plan B Sample)" "," ///
    "Any College Enrollment, 1st Year" "," ///
    "Any College Enrollment, 2nd Year" _n

********************************************************************************
* Helper: run 6 IVs for a given sample and bandwidth, write rows
********************************************************************************
cap program drop _a8_band
program define _a8_band, rclass
    syntax , SAMP(string) BW(integer)

    * sample condition
    local cond_all "all==1"
    if "`samp'" == "all" local cond "`cond_all'"
    else if "`samp'" == "m" local cond "m==1"
    else if "`samp'" == "f" local cond "f==1"

    * ----- (1) grdot -----
    xi: ivreg grdot (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & `cond', cluster(schid)
    local b_grdot   = string(_b[gifted], "%4.2f")
    local se_grdot  = string(_se[gifted], "%4.2f")
    local N_grdot   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_grdot = "**"
    else if `p' < 0.05 local sig_grdot = "*"
    else if `p' < 0.10 local sig_grdot = "+"
    else                local sig_grdot = ""

    * ----- (2) grdot_v2 -----
    xi: ivreg grdot_v2 (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & `cond', cluster(schid)
    local b_grdot2   = string(_b[gifted], "%4.2f")
    local se_grdot2  = string(_se[gifted], "%4.2f")
    local N_grdot2   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_grdot2 = "**"
    else if `p' < 0.05 local sig_grdot2 = "*"
    else if `p' < 0.10 local sig_grdot2 = "+"
    else                local sig_grdot2 = ""

    * ----- (3) grad_v2 -----
    xi: ivreg grad_v2 (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & `cond', cluster(schid)
    local b_grad2   = string(_b[gifted], "%4.2f")
    local se_grad2  = string(_se[gifted], "%4.2f")
    local N_grad2   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_grad2 = "**"
    else if `p' < 0.05 local sig_grad2 = "*"
    else if `p' < 0.10 local sig_grad2 = "+"
    else                local sig_grad2 = ""

    * ----- (4) collot_v2 -----
    xi: ivreg collot_v2 (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & `cond', cluster(schid)
    local b_coll2   = string(_b[gifted], "%4.2f")
    local se_coll2  = string(_se[gifted], "%4.2f")
    local N_coll2   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_coll2 = "**"
    else if `p' < 0.05 local sig_coll2 = "*"
    else if `p' < 0.10 local sig_coll2 = "+"
    else                local sig_coll2 = ""

    * ----- (5) coll_1yr -----
    xi: ivreg coll_1yr (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & `cond', cluster(schid)
    local b_coll1   = string(_b[gifted], "%4.2f")
    local se_coll1  = string(_se[gifted], "%4.2f")
    local N_coll1   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_coll1 = "**"
    else if `p' < 0.05 local sig_coll1 = "*"
    else if `p' < 0.10 local sig_coll1 = "+"
    else                local sig_coll1 = ""

    * ----- (6) any_enroll_yr2 -----
    xi: ivreg any_enroll_yr2 (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & `cond', cluster(schid)
    local b_coll2yr   = string(_b[gifted], "%4.2f")
    local se_coll2yr  = string(_se[gifted], "%4.2f")
    local N_coll2yr   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_coll2yr = "**"
    else if `p' < 0.05 local sig_coll2yr = "*"
    else if `p' < 0.10 local sig_coll2yr = "+"
    else                local sig_coll2yr = ""

    * ----- Write rows for this BW -----
    file write table "BW `bw'" "," ///
        `"`b_grdot'`sig_grdot'"' "," ///
        `"`b_grdot2'`sig_grdot2'"' "," ///
        `"`b_grad2'`sig_grad2'"' "," ///
        `"`b_coll2'`sig_coll2'"' "," ///
        `"`b_coll1'`sig_coll1'"' "," ///
        `"`b_coll2yr'`sig_coll2yr'"' _n

    file write table "," ///
        "(" `"`se_grdot'"' ")" "," ///
        "(" `"`se_grdot2'"' ")" "," ///
        "(" `"`se_grad2'"' ")" "," ///
        "(" `"`se_coll2'"' ")" "," ///
        "(" `"`se_coll1'"' ")" "," ///
        "(" `"`se_coll2yr'"' ")" _n

    file write table "Obs." "," ///
        "`N_grdot'" "," ///
        "`N_grdot2'" "," ///
        "`N_grad2'" "," ///
        "`N_coll2'" "," ///
        "`N_coll1'" "," ///
        "`N_coll2yr'" _n

    file write table "," "," "," "," "," "," _n
end

********************************************************************************
* Panel A: Boys
********************************************************************************

file write table "Panel B. Boys Only" _n

foreach bw in 8 6 10 {
    _a8_band, samp(m) bw(`bw')
}

********************************************************************************
* Panel B: Girls
********************************************************************************

file write table "Panel C. Girls Only" _n

foreach bw in 8 6 10 {
    _a8_band, samp(f) bw(`bw')
}

file close table
display ""
display "Appendix Table A8 created: $out\table_A8_formatted.csv"
display ""

********************************************************************************
*** APPENDIX TABLE A9 – SAT Score Impacts
********************************************************************************

* Assumes:
*   global donut
*   global bw6 bw8 bw10
*   gifted, r, d, dxr, m, f, schid
*   outcomes: has_sat, sat

file close _all
file open table using "$out/table_A9_formatted.csv", write replace

* Column headers
file write table "," "(1)" "," "(2)" _n
file write table "," "Has SAT Score" "," "SAT Score" _n

********************************************************************************
* Panel A: Boys
********************************************************************************

file write table "Panel A. Boys Only" _n

foreach bw in 8 6 10 {

    * ----- (1) Has SAT -----
    xi: ivreg has_sat (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_has   = string(_b[gifted], "%4.2f")
    local se_has  = string(_se[gifted], "%4.2f")
    local N_has   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_has = "**"
    else if `p' < 0.05 local sig_has = "*"
    else if `p' < 0.10 local sig_has = "+"
    else                local sig_has = ""

    * ----- (2) SAT score -----
    xi: ivreg sat (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_sat   = string(_b[gifted], "%4.2f")
    local se_sat  = string(_se[gifted], "%4.2f")
    local N_sat   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_sat = "**"
    else if `p' < 0.05 local sig_sat = "*"
    else if `p' < 0.10 local sig_sat = "+"
    else                local sig_sat = ""

    * Coefficient row
    file write table "BW `bw'" "," ///
        `"`b_has'`sig_has'"' "," ///
        `"`b_sat'`sig_sat'"' _n

    * SE row
    file write table "," ///
        "(" `"`se_has'"' ")" "," ///
        "(" `"`se_sat'"' ")" _n

    * Obs row
    file write table "Obs." "," ///
        "`N_has'" "," ///
        "`N_sat'" _n

    * Blank row
    file write table "," "," _n
}

********************************************************************************
* Panel B: Girls
********************************************************************************

file write table "Panel B. Girls Only" _n

foreach bw in 8 6 10 {

    * ----- (1) Has SAT -----
    xi: ivreg has_sat (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_has   = string(_b[gifted], "%4.2f")
    local se_has  = string(_se[gifted], "%4.2f")
    local N_has   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_has = "**"
    else if `p' < 0.05 local sig_has = "*"
    else if `p' < 0.10 local sig_has = "+"
    else                local sig_has = ""

    * ----- (2) SAT score -----
    xi: ivreg sat (gifted = r d dxr) r dxr ///
        if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_sat   = string(_b[gifted], "%4.2f")
    local se_sat  = string(_se[gifted], "%4.2f")
    local N_sat   = e(N)
    test gifted
    local p = r(p)
    if      `p' < 0.01 local sig_sat = "**"
    else if `p' < 0.05 local sig_sat = "*"
    else if `p' < 0.10 local sig_sat = "+"
    else                local sig_sat = ""

    * Coefficient row
    file write table "BW `bw'" "," ///
        `"`b_has'`sig_has'"' "," ///
        `"`b_sat'`sig_sat'"' _n

    * SE row
    file write table "," ///
        "(" `"`se_has'"' ")" "," ///
        "(" `"`se_sat'"' ")" _n

    * Obs row
    file write table "Obs." "," ///
        "`N_has'" "," ///
        "`N_sat'" _n

    * Blank row
    file write table "," "," _n
}

file close table
display ""
display "Appendix Table A9 created: $out/table_A9_formatted.csv"
display ""

********************************************************************************
*** TABLE 1 - Student & School Characteristics (All, Plan B, Compliers)
*** Uses two datasets:
***   1) ${input}table1_column1.dta  -> column (1)
***   2) ${input}table1_columns2-6.dta -> columns (2)-(6)
********************************************************************************

************************************************************
* STEP 1: Column (1) - All students (dataset 1)
************************************************************

use "${input}table1_column1ulated.dta", clear

* Characteristic variables in the order shown in the paper
global char ///
    white black hispanic frl lep ///
    g2_zscore g2math g2read g3fcat g3math g3read g3svy_enj ///
    sch_black sch_hispanic sch_frl sch_zsat_mean

* Ensure constant and "all" indicator exist
cap confirm variable one
if _rc gen one = 1

cap confirm variable all
* If "all" doesn't exist, treat whole file as all==1
if _rc gen all = 1

* Store column (1) means and SEs as globals so they persist after we switch datasets
foreach v of varlist $char {
    quietly reg `v' one if all==1, cluster(schid) nocons
    local b  = _b[one]
    local se = _se[one]
    global col1_`v'   = string(`b',  "%4.2f")
    global col1se_`v' = string(`se', "%4.2f")
}

* Column 1 sample size
quietly count if all==1
global N_col1 = r(N)

************************************************************
* STEP 2: Columns (2)-(6) - Plan B + IQ 106-124 & Compliers
************************************************************

use "${input}table1_columns2-6.dta", clear

* Make sure these variables exist (adjust names if your data uses , etc.)
* same char list as above:
global char ///
    white black hispanic frl lep ///
    g2_zscore g2math g2read g3fcat g3math g3read g3svy_enj ///
    sch_black sch_hispanic sch_frl sch_zsat_mean
	
gen x=r+116 // rescale running variable

cap confirm variable one
if _rc gen one = 1

* pooled / sex indicators
cap confirm variable all
if _rc gen all = (m==1 | f==1)

* We assume you already have:
*   global donut
*   global bw8
* and variables: gifted, gifted, r, d, dxr, m, f, schid

************************************************************
* Open output file and write headers
************************************************************

file close _all
file open table using "$out/table_1_formatted.csv", write replace

* Column numbers
file write table "," "(1)" "," "(2)" "," "(3)" "," "(4)" "," "(5)" "," "(6)" _n

* Group headers
file write table "," ///
    "All Students" "," ///
    "Plan B + IQ Scores 106-124" "," ///
    "Plan B + IQ Scores 106-124" "," ///
    "Plan B + IQ Scores 106-124" "," ///
    "Compliers" "," ///
    "Compliers" _n

* Subheaders
file write table "," ///
    "All Students" "," ///
    "Pooled" "," ///
    "Boys" "," ///
    "Girls" "," ///
    "Boys" "," ///
    "Girls" _n

************************************************************
* Helper program: one row (means + SEs) for a given variable
************************************************************

cap program drop _t1_row
program define _t1_row
    syntax varname, Label(string)

    local v `varlist'

    * Column (1): All students (from first dataset, stored as globals)
    local b_all  = "${col1_`v'}"
    local se_all = "${col1se_`v'}"

    * Columns (2)-(4): Plan B + IQ 106-124 means (pooled, boys, girls)
    quietly reg `v' one if ${bw8} & all==1, cluster(schid) nocons
    local b_pool  = string(_b[one],  "%4.2f")
    local se_pool = string(_se[one], "%4.2f")

    quietly reg `v' one if ${bw8} & m==1, cluster(schid) nocons
    local b_m  = string(_b[one],  "%4.2f")
    local se_m = string(_se[one], "%4.2f")

    quietly reg `v' one if ${bw8} & f==1, cluster(schid) nocons
    local b_f  = string(_b[one],  "%4.2f")
    local se_f = string(_se[one], "%4.2f")

    * Columns (5)-(6): complier means (boys, girls)
    quietly xi: ivreg gifted_x_`v' (gifted = r d dxr) r dxr ///
        if $donut & ${bw8} & m==1, cluster(schid)
    local b_comp_m  = string(_b[gifted],  "%4.2f")
    local se_comp_m = string(_se[gifted], "%4.2f")

    quietly xi: ivreg gifted_x_`v' (gifted = r d dxr) r dxr ///
        if $donut & ${bw8} & f==1, cluster(schid)
    local b_comp_f  = string(_b[gifted],  "%4.2f")
    local se_comp_f = string(_se[gifted], "%4.2f")

    * Write means row
    file write table `"`label'"' "," ///
        "`b_all'" "," ///
        "`b_pool'" "," ///
        "`b_m'" "," ///
        "`b_f'" "," ///
        "`b_comp_m'" "," ///
        "`b_comp_f'" _n

    * Write SE row
    file write table "," ///
        "(" `"`se_all'"' ")" "," ///
        "(" `"`se_pool'"' ")" "," ///
        "(" `"`se_m'"' ")" "," ///
        "(" `"`se_f'"' ")" "," ///
        "(" `"`se_comp_m'"' ")" "," ///
        "(" `"`se_comp_f'"' ")" _n
end

************************************************************
* Panel: Student Characteristics
************************************************************

file write table "Student Characteristics" _n

_t1_row white,     label("White")
_t1_row black,     label("Black")
_t1_row hispanic,  label("Hispanic")
_t1_row frl,       label("FRL")
_t1_row lep,       label("ELL")
_t1_row g2_zscore, label("G2 Avg. Test z-score")
_t1_row g2math,    label("G2 Math Test z-score")
_t1_row g2read,    label("G2 Reading Test z-score")
_t1_row g3fcat,    label("G3 Avg. Test z-score")
_t1_row g3math,    label("G3 Math Test z-score")
_t1_row g3read,    label("G3 Reading Test z-score")
_t1_row g3svy_enj, ///
    label("G3 Enjoy Learning at School (1=least; 5=most)")

file write table "" _n

************************************************************
* Panel: Student's School Characteristics
************************************************************

file write table "Student's School Characteristics" _n

_t1_row sch_black,     label("Share Black")
_t1_row sch_hispanic,  label("Share Hispanic")
_t1_row sch_frl,       label("Share FRL")
_t1_row sch_zsat_mean, label("Avg. Test z-score")

file write table "" _n

************************************************************
* Observations row
************************************************************

* Plan B sample sizes (columns 2-4) from this dataset
quietly count if ${bw8} & all==1
local N_planb_all = r(N)

quietly count if ${bw8} & m==1
local N_planb_m = r(N)

quietly count if ${bw8} & f==1
local N_planb_f = r(N)

file write table "Observations" "," ///
    "${N_col1}" "," ///
    "`N_planb_all'" "," ///
    "`N_planb_m'" "," ///
    "`N_planb_f'" "," ///
    "--" "," "--" _n

file close table
display ""
display "Table 1 created: $out/table_1_formatted.csv"
display ""


********************************************************************************
*** APPENDIX TABLE D1 – GEM Analysis (RD around 5th grade math cutoff)
********************************************************************************

use "${input}planb_rdsmpl.dta", clear

* Outcomes in column order:
* (1) g2_zscore
* (2) g3fcat
* (3) pr_collot
* (4) gifted
* (5) gem6 (first stage)
* (6) collot (reduced form)
* (7) collot 2SLS on gem6

drop pr_collot_g2nai pr_collot_g2sat

global main_d1 g2_zscore g3fcat pr_collot gifted gem6 collot

file close _all
file open table using "$out/table_D1_formatted.csv", write replace

* Column headers
file write table "," "(1)" "," "(2)" "," "(3)" "," "(4)" "," "(5)" "," "(6)" "," "(7)" _n
file write table "," ///
    "Grade 2 Avg. z-score" "," ///
    "Grade 3 Avg. z-score" "," ///
    "Predicted On-time Enrollment" "," ///
    "Identified as Gifted" "," ///
    "GEM Enrollment, 6th Grade" "," ///
    "Grad HS On-time + Enrolled Within 1 Yr (RF)" "," ///
    "Grad HS On-time + Enrolled Within 1 Yr (2SLS)" _n

********************************************************************************
* Helper program: one BW row for a given sample (m or f)
********************************************************************************
cap program drop _d1_row
program define _d1_row
    syntax , SAMP(string) BW(integer)

    local cond "`samp'==1 & bw`bw'gem==1"

    * (1) Grade 2 Avg z-score
    quietly reg g2_zscore gemd gemr gemdxr if `cond', cluster(schid)
    local b_g2  = string(_b[gemd], "%4.2f")
    local se_g2 = string(_se[gemd], "%4.2f")
    local N_g2  = e(N)
    test gemd
    local p = r(p)
    if      `p' < 0.01 local sig_g2 = "**"
    else if `p' < 0.05 local sig_g2 = "*"
    else if `p' < 0.10 local sig_g2 = "+"
    else                local sig_g2 = ""

    * (2) Grade 3 Avg z-score
    quietly reg g3fcat gemd gemr gemdxr if `cond', cluster(schid)
    local b_g3  = string(_b[gemd], "%4.2f")
    local se_g3 = string(_se[gemd], "%4.2f")
    local N_g3  = e(N)
    test gemd
    local p = r(p)
    if      `p' < 0.01 local sig_g3 = "**"
    else if `p' < 0.05 local sig_g3 = "*"
    else if `p' < 0.10 local sig_g3 = "+"
    else                local sig_g3 = ""

    * (3) Predicted on-time enrollment
    quietly reg pr_collot gemd gemr gemdxr if `cond', cluster(schid)
    local b_pr  = string(_b[gemd], "%4.2f")
    local se_pr = string(_se[gemd], "%4.2f")
    local N_pr  = e(N)
    test gemd
    local p = r(p)
    if      `p' < 0.01 local sig_pr = "**"
    else if `p' < 0.05 local sig_pr = "*"
    else if `p' < 0.10 local sig_pr = "+"
    else                local sig_pr = ""

    * (4) Identified as gifted
    quietly reg gifted gemd gemr gemdxr if `cond', cluster(schid)
    local b_gft  = string(_b[gemd], "%4.2f")
    local se_gft = string(_se[gemd], "%4.2f")
    local N_gft  = e(N)
    test gemd
    local p = r(p)
    if      `p' < 0.01 local sig_gft = "**"
    else if `p' < 0.05 local sig_gft = "*"
    else if `p' < 0.10 local sig_gft = "+"
    else                local sig_gft = ""

    * (5) First stage: GEM enrollment
    quietly reg gem6 gemd gemr gemdxr if `cond', cluster(schid)
    local b_fs  = string(_b[gemd], "%4.2f")
    local se_fs = string(_se[gemd], "%4.2f")
    local N_fs  = e(N)
    test gemd
    local p = r(p)
    if      `p' < 0.01 local sig_fs = "**"
    else if `p' < 0.05 local sig_fs = "*"
    else if `p' < 0.10 local sig_fs = "+"
    else                local sig_fs = ""

    * (6) Reduced form: outcome on gemd
    quietly reg collot gemd gemr gemdxr if `cond', cluster(schid)
    local b_rf  = string(_b[gemd], "%4.2f")
    local se_rf = string(_se[gemd], "%4.2f")
    local N_rf  = e(N)
    test gemd
    local p = r(p)
    if      `p' < 0.01 local sig_rf = "**"
    else if `p' < 0.05 local sig_rf = "*"
    else if `p' < 0.10 local sig_rf = "+"
    else                local sig_rf = ""

    * (7) 2SLS: collot on gem6, IV = gemd
    quietly xi: ivreg collot (gem6 = gemd gemr gemdxr) gemr gemdxr ///
        if `cond', cluster(schid)
    local b_2sls  = string(_b[gem6], "%4.2f")
    local se_2sls = string(_se[gem6], "%4.2f")
    local N_2sls  = e(N)
    test gem6
    local p = r(p)
    if      `p' < 0.01 local sig_2sls = "**"
    else if `p' < 0.05 local sig_2sls = "*"
    else if `p' < 0.10 local sig_2sls = "+"
    else                local sig_2sls = ""

    * Coefficient row
    file write table "BW `bw'" "," ///
        `"`b_g2'`sig_g2'"' "," ///
        `"`b_g3'`sig_g3'"' "," ///
        `"`b_pr'`sig_pr'"' "," ///
        `"`b_gft'`sig_gft'"' "," ///
        `"`b_fs'`sig_fs'"' "," ///
        `"`b_rf'`sig_rf'"' "," ///
        `"`b_2sls'`sig_2sls'"' _n

    * SE row
    file write table "," ///
        "(" `"`se_g2'"' ")" "," ///
        "(" `"`se_g3'"' ")" "," ///
        "(" `"`se_pr'"' ")" "," ///
        "(" `"`se_gft'"' ")" "," ///
        "(" `"`se_fs'"' ")" "," ///
        "(" `"`se_rf'"' ")" "," ///
        "(" `"`se_2sls'"' ")" _n

    * Obs row
    file write table "Obs." "," ///
        "`N_g2'" "," ///
        "`N_g3'" "," ///
        "`N_pr'" "," ///
        "`N_gft'" "," ///
        "`N_fs'" "," ///
        "`N_rf'" "," ///
        "`N_2sls'" _n

    * Blank row
    file write table "," "," "," "," "," "," "," _n
end

********************************************************************************
* Panel A: Boys
********************************************************************************

file write table "Panel A. Boys Only" _n

* Order 20, 15, 25 to match the published table
foreach bw in 20 15 25 {
    _d1_row, samp(m) bw(`bw')
}

********************************************************************************
* Panel B: Girls
********************************************************************************

file write table "Panel B. Girls Only" _n

foreach bw in 20 15 25 {
    _d1_row, samp(f) bw(`bw')
}

file close table
display ""
display "Appendix Table D1 created: $out/table_D1_formatted.csv"
display ""

********************************************************************************
*** TABLE 7
********************************************************************************

* Summary of Plan B RD estimated impacts
********************************************************************************

* global for bandwidths
global bw10 "inrange(x,104,126) & donut==0" 
global bw8 "inrange(x,106,124) & donut==0" 
global bw6 "inrange(x,108,122) & donut==0" 

use "${input}planb_rdsmpl.dta", clear

gen notgifted = (1-gifted)
gen x=r+116 // rescale running variable

* open table shell 
file close _all
file open table using "$out\table_7.csv", write replace
file write table "var,y0_m,y1_m,delta_m,,y0_f,y1_f,delta_f,,diff_xm,p_val" _n // 9 columns

sum sat, det
gen sat_zscore = (sat-r(mean))/r(sd)

foreach var in gifted d r dxr {
	gen `var'_X_m = `var'*m
}

* create shorter names 
rename peer_g35fcat_g68_math pq_g35fcat_g68_math 
rename peer_g35fcat_g68_lang pq_g35fcat_g68_lang

* loop through the set of outcomes:
foreach var in gha gem6 pq_g35fcat_g68_math pq_g35fcat_g68_lang alg8 no_susp_ms peer_g35fcat_hs_math peer_g35fcat_hs_lang math_gpa_hs lang_arts_gpa_hs gpa_hs num_ap_course fcat678_avgany fcat678_math fcat678_read maxpsattotpct maxpsatmathpct maxpsatreadpct collot {

	gen `var'_x_notgifted = `var'*notgifted 
	gen `var'_x_gifted = `var'*gifted 

	* estimate male complier outcomes
	*- non-gifted compliers
	xi: ivreg `var'_x_notgifted (notgifted = d r dxr) r dxr if ${bw8} & m==1, cluster(schid)
	local complier_y0_m = _b[notgifted]
	local se_y0_m = _se[notgifted]
	*- gifted compliers
	xi: ivreg `var'_x_gifted (gifted  = d r dxr) r dxr if ${bw8} & m==1, cluster(schid)
	local complier_y1_m = _b[gifted]
	local se_y1_m = _se[gifted]

	* estimate female complier outcomes
	*- non-gifted compliers
	xi: ivreg `var'_x_notgifted (notgifted  = d r dxr) r dxr if ${bw8} & f==1, cluster(schid)
	local complier_y0_f = _b[notgifted]
	local se_y0_f = _se[notgifted]
	*- gifted compliers
	xi: ivreg `var'_x_gifted (gifted  = d r dxr) r dxr if ${bw8} & f==1, cluster(schid)
	local complier_y1_f = _b[gifted]
	local se_y1_f = _se[gifted]
	
	* LATE
	xi: ivreg `var' (gifted  = d r dxr) r dxr if ${bw8} & m==1, cluster(schid)
	local late_m = _b[gifted]
	local late_m_se = _se[gifted]
	
	test gifted
	local p_val = r(p)
	
	local sig_m ""
	if `p_val'<.1 local sig_m "+"
	if `p_val'<.05 local sig_m "*"
	if `p_val'<.01 local sig_m "**"
	
	xi: ivreg `var' (gifted  = d r dxr) r dxr if ${bw8} & f==1, cluster(schid)
	local late_f = _b[gifted]
	local late_f_se = _se[gifted]
	
	test gifted
	local p_val = r(p)
	
	local sig_f ""
	if `p_val'<.1 local sig_f "*"
	if `p_val'<.05 local sig_f "**"
	if `p_val'<.01 local sig_f "***"
	
	* TEST BOY LATE = GIRL LATE
	xi: ivreg `var' (gifted gifted_X_m = m d r dxr d_X_m r_X_m dxr_X_m) m r r_X_m dxr dxr_X_m if ${bw8}, cluster(schid)
	local late_xm = _b[gifted_X_m]
	local late_xm_se = _se[gifted_X_m]

	test gifted_X_m
	local p_val = r(p)

	local sig_xm ""
	if `p_val'<.1 local sig_xm "*"
	if `p_val'<.05 local sig_xm "**"
	if `p_val'<.01 local sig_xm "***"
	
	**************  ADD ROW TO TABLE *****************
	display "`var'"

	* rows for point estimates
	
	file write table "`var'"
	
	* male results
	file write table "," (char(34)) (string(`complier_y0_m',"%15.2fc")) (char(34))
	file write table "," (char(34)) (string(`complier_y1_m',"%15.2fc")) (char(34))
	file write table "," (char(34)) (string(`late_m',"%15.2fc")) "`sig_m'" (char(34))
	
	file write table ","
	
	* female results
	file write table "," (char(34)) (string(`complier_y0_f',"%15.2fc")) (char(34))
	file write table "," (char(34)) (string(`complier_y1_f',"%15.2fc")) (char(34))
	file write table "," (char(34)) (string(`late_f',"%15.2fc")) "`sig_f'" (char(34))
	
	file write table ","

	* male-female diff
	file write table "," (char(34)) (string(`late_xm',"%15.2fc")) "`sig_xm'" (char(34))
	file write table "," (char(34)) (string(`p_val',"%15.2fc")) (char(34))

	file write table _n // end estimate row
	
	* rows for SEs
	
	* male results
	file write table ",[" (string(`se_y0_m' ,"%15.3fc")) "]"
	file write table ",[" (string(`se_y1_m' ,"%15.3fc")) "]"
	file write table ",[" (string(`late_m_se' ,"%15.3fc")) "]"
		
	file write table ","
	
	* female results
	file write table ",[" (string(`se_y0_f' ,"%15.3fc")) "]"
	file write table ",[" (string(`se_y1_f' ,"%15.3fc")) "]"
	file write table ",[" (string(`late_f_se' ,"%15.3fc")) "]"
	
	file write table ","

	* male-female diff
	file write table ",[" (string(`late_xm_se' ,"%15.3fc")) "]"
	file write table ","

	file write table _n // end estimate row
}

file close table // close table


********************************************************************************
* Appendix Table D2
********************************************************************************

* GEM Complier comparison
********************************************************************************

* global for bandwidths
*----------------------
global bw10 "inrange(x,104,126) & donut==0" 
global bw8 "inrange(x,106,124) & donut==0" 
global bw6 "inrange(x,108,122) & donut==0" 

cap program drop compy0y1
program define compy0y1
	args dep treat grp bw  
	 // 4 arguments for program: outcome / treatment variable / sample / BW
	
	cap drop t 
	cap drop c 
	gen t = `treat' 
	gen c = 1-t 
	
	cap drop `dep'_x_t 
	cap drop `dep'_x_c 
	gen `dep'_x_t = `dep'*t
	gen `dep'_x_c = `dep'*c
	cap gen txr = t*r 

	constraint 1 [g0eqn]c = [g1eqn]t 

	* estimate mean potential outcomes for compliers 
		*- untreated compliers
		xi: ivreg `dep'_x_c (c = d r dxr) r dxr if ${bw`bw'} & `grp'==1, cluster(schid)
		global beta_y0 = _b[c]
		global se_y0 = _se[c]
		*- treated compliers
		xi: ivreg `dep'_x_t (t = d r dxr) r dxr if ${bw`bw'} & `grp'==1, cluster(schid)
		global beta_y1 = _b[t]
		global se_y1 = _se[t]
		*- 3SLS estimates for pooled compliers 
		global g0eqn "(g0eqn: `dep'_x_c c r txr)"
		global g1eqn "(g1eqn: `dep'_x_t t r txr)"
		global enlist "(c t txr)"
		global exlist "(d dxr r)" 	
		reg3 $g0eqn $g1eqn if ${bw`bw'} & `grp'==1, endog($enlist) exog($exlist) constr(1) ireg3
		global beta_y01 = [g1eqn]_b[t]
		global se_y01 = [g1eqn]_se[t]
	* estimate treatment effect 
		xi: ivreg `dep' (t = d r dxr) r dxr if ${bw`bw'} & `grp'==1, cluster(schid)
		global beta_diff = _b[t]
		global se_diff = _se[t]
	
end	

* 1. Compliers who participate in GEM due to passing IQ threshold for gifted 
*	 We can only estimate these for boys since there is no threshold-crossing effect for girls 
*	 The column named m_y01 contains the 3SLS estimates for boys

use "${input}planb_rdsmpl.dta", clear

gen x=r+116 // rescale running variable

global groups = "f m" 

global depvars = "white black hispanic frl lep prntlang_eng g2_zscore g2math g2read g3fcat g3math g3read g3read g3math enjoy_g3 sch_black sch_hispanic sch_frl sch_medhhy sch_zg5_mean" 

	matrix drop _all 

	foreach var in $depvars {
		
			foreach grp in $groups  {		
				compy0y1 `var' gem6 `grp' 8
				matrix results_`grp' = ($beta_y0 , $beta_y1 , $beta_diff , $beta_y01 \ $se_y0 , $se_y1 , $se_diff , $se_y01 )
			}
			
			matrix results_`var' = (results_m, results_f)
			mat coln results_`var' = m_y0 m_y1 m_tot m_y01 f_y0 f_y1 f_tot f_y01 
		
		mat rown results_`var' = `var'_coef `var'_se 
	}

* Build table1 by stacking all results matrices
matrix table1 = results_white
foreach var in black hispanic frl lep prntlang_eng g2_zscore g2math g2read g3fcat g3math g3read enjoy_g3 sch_black sch_hispanic sch_frl sch_medhhy sch_zg5_mean {
    matrix table1 = (table1 \ results_`var')
}

matrix list table1 

* Keep only the m_y01 column (3SLS complier means for boys)
matrix table1_y01 = table1[., "m_y01"]

matrix list table1_y01 

* Save matrix to CSV file
preserve
clear
svmat table1_y01, names(col)
gen variable = ""
local row = 1
replace variable = "white_coef" in `row'
local row = `row' + 1
replace variable = "white_se" in `row'
foreach var in black hispanic frl lep g2_zscore g2math g2read g3fcat g3math g3read g3svy_enj sch_black sch_hispanic sch_frl sch_medhhy sch_zg5_mean {
    local row = `row' + 1
    replace variable = "`var'_coef" in `row'
    local row = `row' + 1
    replace variable = "`var'_se" in `row'
}
order variable
export delimited using "${out}/table_D2_col1.csv", replace
restore


* 2. Compliers who participate in GEM due to passing g5math threshold for GEM 
*	 The column named m_y01 contains the 3SLS estimates for boys

global bw20 "bw20gem==1" 

use "${input}planb_rdsmpl.dta", clear
drop if cohort==2012

replace r = gemr 
replace d = gemd 
replace dxr = gemdxr

global groups = "m f" 

	matrix drop _all 

	foreach var in $depvars {
		
			foreach grp in $groups  {		
				compy0y1 `var' gem6 `grp' 20
				matrix results_`grp' = ($beta_y0 , $beta_y1 , $beta_diff , $beta_y01 \ $se_y0 , $se_y1 , $se_diff , $se_y01 )
			}
			
			matrix results_`var' = (results_m, results_f)
			mat coln results_`var' = m_y0 m_y1 m_tot m_y01 f_y0 f_y1 f_tot f_y01
		
		mat rown results_`var' = `var'_coef `var'_se 
	}

* Build table1 by stacking all results matrices
matrix table1 = results_white
foreach var in black hispanic frl lep g2_zscore g2math g2read g3fcat g3math g3read enjoy_g3 sch_black sch_hispanic sch_frl sch_medhhy sch_zg5_mean {
    matrix table1 = (table1 \ results_`var')
}

matrix list table1 

* Keep only the m_y01 column (3SLS complier means for boys)
matrix table1_y01 = table1[., "m_y01"]

matrix list table1_y01 

* Save matrix to CSV file
preserve
clear
svmat table1_y01, names(col)
gen variable = ""
local row = 1
replace variable = "white_coef" in `row'
local row = `row' + 1
replace variable = "white_se" in `row'
foreach var in black hisp frl lep g2_zscore g2math g2read g3fcat g3math g3read enjoy_g3 sch_black sch_hispanic sch_frl sch_medhhy sch_zg5_mean {
    local row = `row' + 1
    replace variable = "`var'_coef" in `row'
    local row = `row' + 1
    replace variable = "`var'_se" in `row'
}
order variable
export delimited using "$out/table_D2_col2.csv", replace
restore

********************************************************************************
*** Appendix Table A7
********************************************************************************

* F-test linearity vs. dummies for each IQ
********************************************************************************

use "${input}planb_rdsmpl.dta", clear

gen x=r+116 // rescale running variable

tab x, gen(iq)
forval bw=4(1)15 {
	global bw`bw' "inrange(x,114-`bw',116+`bw') & donut==0"
}
matrix drop _all 

foreach sex in m f {

	matrix table_A7_`sex' = (.,.)
	
	forval bw=4(1)15 {
		reg collot i.x if ${bw`bw'} & `sex'==1
		estimates store dummies
		local ur_rss=`e(rss)'
		local ur_dof=`e(df_r)'
		reg collot d r dxr if ${bw`bw'} & `sex'==1 
		estimates store linear
		local r_rss=`e(rss)'
		local r_dof=`e(df_r)'
		local q = `r_dof'-`ur_dof'
		local rmse = `e(rmse)'
		// ftest dummies linear
		local F = ((`r_rss'-`ur_rss')/`q')/(`ur_rss'/`ur_dof') in `bw'
		local p = Ftail(`q', `ur_dof', ((`r_rss'-`ur_rss')/`q')/(`ur_rss'/`ur_dof')) in `bw'
		local rmse = `rmse' in `bw'
		matrix table_A7_`sex' = (table_A7_`sex' \ `rmse', `p')
	}

}

matrix table_A7 = (table_A7_m, table_A7_f)
matrix coln table_A7 = Boys_RMSE Boys_p Girls_RMSE Girls_p
matrix rown table_A7 = . 4 5 6 7 8 9 10 11 12 13 14 15
matrix list table_A7

* Save matrix to CSV file
preserve
clear
svmat table_A7, names(col)
gen bandwidth = .
replace bandwidth = 4 in 2
forval i = 5/15 {
	local row = `i' - 2
	replace bandwidth = `i' in `row'
}
order bandwidth
export delimited using "$out/table_A7.csv", replace
restore

********************************************************************************
* APPENDIX TABLES A5 and A6
********************************************************************************

* setting for inclusion of donut observations
global donut="donut==0"

********************************************************************************
* global for bandwidths
*----------------------
global bw10 "inrange(x,104,126) & donut==0" 
global bw8 "inrange(x,106,124) & donut==0" 
global bw6 "inrange(x,108,122) & donut==0" 

use "${input}planb_rdsmpl.dta", clear

gen x=r+116 // rescale running variable

* set index values
local below = 111
local above = 119
local k = 3

*** Boys

* open table shell 
file close _all
file open table using "$out\table_a5_boys.csv", write replace
file write table ",3,4,5,6,7,8,9,10,11,12" _n 

forvalues i=0(1)11 {
	
	file write table "`k'"
	
	* Row of estimates 

	forvalues j=0(1)9 {
	
		** Reduced form

		* boys
		reg collot r d dxr if $donut & inrange(x,`below',`above') & m==1, cluster(schid)
		file write table "," (char(34)) (string(_b[d],"%15.3fc")) (char(34))
		
		local above = `above'+1
		
	}
	
	file write table _n // end row
	 
	local above = 119
	
	* Row of SEs
	
	forvalues j=0(1)9 {
	
		** Reduced form

		* boys
		reg collot r d dxr if $donut & inrange(x,`below',`above') & m==1, cluster(schid)
		file write table "," "'" "(" (string(_se[d],"%15.3fc")) ")"
		
		local above = `above'+1
		
	}
	
	file write table _n // end row

	* advance the index tracking the row label
	local k = `k'+1
	
	* advance the index tracking the bandwidth on the left
	local below = `below'-1
	
	* reset the index tracking the bandwidth on the right
	local above = 119	
}

file close table

*** Boys, 2SLS

* set index values
local below = 111
local above = 119
local k = 3

* open table shell 
file close _all
file open table using "$out\table_a6_boys.csv", write replace
file write table ",3,4,5,6,7,8,9,10,11,12" _n 

forvalues i=0(1)11 {
	
	file write table "`k'"
	
	* Row of estimates 

	forvalues j=0(1)9 {
	
		** Reduced form

		* boys
		xi: ivreg collot (gifted = d r dxr) r dxr if $donut & inrange(x,`below',`above') & m==1, cluster(schid)
		file write table "," (char(34)) (string(_b[gifted],"%15.3fc")) (char(34))
		
		local above = `above'+1
		
	}
	
	file write table _n // end row
	 
	local above = 119
	
	* Row of SEs
	
	forvalues j=0(1)9 {
	
		** Reduced form

		* boys
		xi: ivreg collot (gifted = d r dxr) r dxr if $donut & inrange(x,`below',`above') & m==1, cluster(schid)
		file write table "," "'" "(" (string(_se[gifted],"%15.3fc")) ")"
		
		local above = `above'+1
		
	}
	
	file write table _n // end row

	* advance the index tracking the row label
	local k = `k'+1
	
	* advance the index tracking the bandwidth on the left
	local below = `below'-1
	
	* reset the index tracking the bandwidth on the right
	local above = 119	
}

file close table

* set index values
local below = 111
local above = 119
local k = 3

*** Girls

* open table shell 
file close _all
file open table using "$out\table_a5_girls.csv", write replace
file write table ",3,4,5,6,7,8,9,10,11,12" _n 

forvalues i=0(1)11 {
	
	file write table "`k'"
	
	* Row of estimates 

	forvalues j=0(1)9 {
	
		** Reduced form

		* boys
		reg collot r d dxr if $donut & inrange(x,`below',`above') & f==1, cluster(schid)
		file write table "," (char(34)) (string(_b[d],"%15.3fc")) (char(34))
		
		local above = `above'+1
		
	}
	
	file write table _n // end row
	 
	local above = 119
	
	* Row of SEs
	
	forvalues j=0(1)9 {
	
		** Reduced form

		* boys
		reg collot r d dxr if $donut & inrange(x,`below',`above') & f==1, cluster(schid)
		file write table "," "'" "(" (string(_se[d],"%15.3fc")) ")"
		
		local above = `above'+1
		
	}
	
	file write table _n // end row

	* advance the index tracking the row label
	local k = `k'+1
	
	* advance the index tracking the bandwidth on the left
	local below = `below'-1
	
	* reset the index tracking the bandwidth on the right
	local above = 119	
}

file close table

*** Girls 2SLS

* set index values
local below = 111
local above = 119
local k = 3

* open table shell 
file close _all
file open table using "$out\table_a6_girls.csv", write replace
file write table ",3,4,5,6,7,8,9,10,11,12" _n 

forvalues i=0(1)11 {
	
	file write table "`k'"
	
	* Row of estimates 

	forvalues j=0(1)9 {
	
		** Reduced form

		* boys
		xi: ivreg collot (gifted = d r dxr) r dxr if $donut & inrange(x,`below',`above') & f==1, cluster(schid)
		file write table "," (char(34)) (string(_b[gifted],"%15.3fc")) (char(34))
		
		local above = `above'+1
		
	}
	
	file write table _n // end row
	 
	local above = 119
	
	* Row of SEs
	
	forvalues j=0(1)9 {
	
		** Reduced form

		* boys
		xi: ivreg collot (gifted = d r dxr) r dxr if $donut & inrange(x,`below',`above') & f==1, cluster(schid)
		file write table "," "'" "(" (string(_se[gifted],"%15.3fc")) ")"
		
		local above = `above'+1
		
	}
	
	file write table _n // end row

	* advance the index tracking the row label
	local k = `k'+1
	
	* advance the index tracking the bandwidth on the left
	local below = `below'-1
	
	* reset the index tracking the bandwidth on the right
	local above = 119	
}

file close table

********************************************************************************
*** Appendix Table A1
********************************************************************************

use "${input}appendix_table_a1.dta", clear

* set global
global xs = "gr3zread gr3zmath female black hispanic frl lep medhhy nai enjoy_g3 gr4cavgLread gr4cavgLmath gr4cpctgifted"

*----------------------------------------------
* Column 1: Plan B Gifted - Not High Achievers
*----------------------------------------------
preserve 
	gen donut=inrange(x,114,116)
	gen bw8 = inrange(x,106,124)
	keep if gf==1 & bw8==1 & donut==0
	matrix col1 = (.)
	local x=0
	foreach var in $xs {
		local x = `x'+1
			cap gen tr1_x_`var' = tr1*`var' 
			xi: ivreg tr1_x_`var' (tr1 = diq riq dxriq) riq dxriq
			matrix col1 = (col1 \ _b[tr1]) 
		}
	matrix coln col1 = col_1
	matrix rown col1 = ${rows}
	matrix list col1	
restore 

*----------------------------------------------
* Column 2: Non-Gifted High Achievers
*----------------------------------------------
preserve 
	keep if ha==1 
	matrix col2 = (.)
	local x=0
	foreach var in $xs {
		local x = `x'+1
			cap gen tr1_x_`var' = tr1*`var' 
			xi: ivreg tr1_x_`var' (tr1 = d r dxr) r dxr
			matrix col2 = (col2 \ _b[tr1]) 
		}
	matrix coln col2 = col_2 
	matrix rown col2 = ${rows}
	matrix list col2	
restore 

*----------------------------------------------
* Column 3: Minority, Non-Gifted High Achievers
*----------------------------------------------
preserve 
	keep if ha==1 & (minority==1)
	matrix col3 = (.)
	local x=0
	foreach var in $xs {
		local x = `x'+1
			cap gen tr1_x_`var' = tr1*`var' 
			xi: ivreg tr1_x_`var' (tr1 = d r dxr) r dxr
			matrix col3 = (col3 \ _b[tr1]) 
		}
	matrix coln col3 = col_3
	matrix rown col3 = ${rows}
	matrix list col3	
restore 

*----------------------------------------------
* Table 
*----------------------------------------------
matrix table_a1 = (col1, col2, col3)
matrix list table_a1

* Save matrix to Excel file
preserve
clear
svmat table_a1, names(col)

* Create variable names
gen variable = ""
local varlist "blank gr3zread gr3zmath female black hispanic frl lep medhhy nai enjoy_g3 gr4cavgLread gr4cavgLmath gr4cpctgifted"
local row = 1
foreach var in `varlist' {
    replace variable = "`var'" in `row'
    local row = `row' + 1
}
order variable
export excel using "${out}/table_A1.xlsx", firstrow(variables) replace
restore

********************************************************************************
*** APPENDIX TABLE A2 – Sample Selection Tests (formatted CSV)
********************************************************************************

*   global selection   // e.g. "smpl"
*   global donut
*   global bw6 bw8 bw10
*   $linear includes d as the treatment regressor
*   m, f, d, schid are defined

use "${input}appendix_table_a2.dta", clear

gen x=r+116 // rescale running variable
global linear "d r dxr" 
global selection = "smpl"

* Take the first (only) selection variable
local sel : word 1 of $selection

file close _all
file open table using "$out\table_A2_formatted.csv", write replace

* ----------------------------------------------------------------------
* Header rows
* ----------------------------------------------------------------------

* Column numbers
file write table "," "(1)" "," "(2)" "," "(3)" _n

* Column labels
file write table "," "Pooled" "," "Boys" "," "Girls" _n

********************************************************************************
* Loop over bandwidths: 8, 6, 10
********************************************************************************

foreach bw in 8 6 10 {

    * ============================
    * Pooled regression
    * ============================
    quietly reg `sel' $linear if $donut & ${bw`bw'}, cluster(schid)
    local b_pooled    = string(_b[d],      "%4.2f")
    local se_pooled   = string(_se[d],     "%4.2f")
    local mean_pooled = string(_b[_cons],  "%4.3f")
    local N_pooled    = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_pooled = "**"
    else if `p' < 0.05 local sig_pooled = "*"
    else if `p' < 0.10 local sig_pooled = "+"
    else                local sig_pooled = ""

    * ============================
    * Boys regression
    * ============================
    quietly reg `sel' $linear if $donut & ${bw`bw'} & m==1, cluster(schid)
    local b_boys    = string(_b[d],      "%4.2f")
    local se_boys   = string(_se[d],     "%4.2f")
    local mean_boys = string(_b[_cons],  "%4.3f")
    local N_boys    = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_boys = "**"
    else if `p' < 0.05 local sig_boys = "*"
    else if `p' < 0.10 local sig_boys = "+"
    else                local sig_boys = ""

    * ============================
    * Girls regression
    * ============================
    quietly reg `sel' $linear if $donut & ${bw`bw'} & f==1, cluster(schid)
    local b_girls    = string(_b[d],      "%4.2f")
    local se_girls   = string(_se[d],     "%4.2f")
    local mean_girls = string(_b[_cons],  "%4.3f")
    local N_girls    = e(N)
    test d
    local p = r(p)
    if      `p' < 0.01 local sig_girls = "**"
    else if `p' < 0.05 local sig_girls = "*"
    else if `p' < 0.10 local sig_girls = "+"
    else                local sig_girls = ""

    * ---------------------------
    * Write rows for this BW
    * ---------------------------

    * Coefficient row
    file write table "BW `bw'," ///
        `"`b_pooled'`sig_pooled'"' "," ///
        `"`b_boys'`sig_boys'"' "," ///
        `"`b_girls'`sig_girls'"' _n

    * SE row
    file write table "," ///
        "(" `"`se_pooled'"' ")" "," ///
        "(" `"`se_boys'"'   ")" "," ///
        "(" `"`se_girls'"'  ")" _n

    * Mean Below Threshold row (from _b[_cons])
    file write table "Mean Below Threshold," ///
        "`mean_pooled'," ///
        "`mean_boys'," ///
        "`mean_girls'" _n

    * Observations row
    file write table "Obs.," ///
        "`N_pooled'," ///
        "`N_boys'," ///
        "`N_girls'" _n

    * Blank row between bandwidth blocks
    file write table "," "," "," _n
}

file close table
display ""
display "Appendix Table A2 created: $out\table_A2_formatted.csv"
display ""

********************************************************************************	
***** Appendix Table C2
********************************************************************************	

use "${input}appendix_table_c2.dta", clear 

***********	
** BOYS **
***********	
* first stage
reg tr d r dxr if m==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("In GHA Class") addtext(Sample, Boys) keep(d)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes nor2 replace
	
* reduced form for gr 3 test scores 
reg g3rm d r dxr if m==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("Gr 3 Test") addtext(Sample, Boys) keep(d)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes append 
* reduced form for gr 3 non-cog 
reg hi d r dxr if m==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("Gr 3 High NC") addtext(Sample, Boys) keep(d)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes append 
		

* 2SLS for GEM in Gr 6
xi: ivreg gem6 (tr = d r dxr) r dxr if m==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("GEM Gr6") addtext(Sample, Boys) keep(tr)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes nor2 append 
* 2SLS for Algebra in Gr 6
xi: ivreg alg8 (tr = d r dxr) r dxr if m==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("Alg Gr8") addtext(Sample, Boys) keep(tr)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes nor2 append 
* 2SLS for Gr 6-8 Peer Quality
xi: ivreg peer_g35fcat_g68 (tr = d r dxr) r dxr if m==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("Peer Qual") addtext(Sample, Boys) keep(tr)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes nor2 append 	
* 2SLS for No Suspensions in Gr 6-8 
xi: ivreg no_susp_ms (tr = d r dxr) r dxr if m==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("No Susp MS") addtext(Sample, Boys) keep(tr)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes nor2 append 	
* 2SLS for gr 6-8 test scores 
xi: ivreg fcat678_avgany (tr = d r dxr) r dxr if m==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("Gr 6-8 Test") addtext(Sample, Boys) keep(tr)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes nor2 append 
* 2SLS for gr 6-8 test scores 
xi: ivreg fcat678_math (tr = d r dxr) r dxr if m==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("Gr 6-8 Math") addtext(Sample, Boys) keep(tr)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes nor2 append 
* 2SLS for gr 6-8 test scores 
xi: ivreg fcat678_read (tr = d r dxr) r dxr if m==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("Gr 6-8 Read") addtext(Sample, Boys) keep(tr)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes nor2 append 

***********	
** GIRLS **
***********	
* first stage
reg tr d r dxr if f==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("In GHA Class") addtext(Sample, Girls) keep(d)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes nor2 append 

* reduced form for gr 3 test scores 
reg g3rm d r dxr if f==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("Gr 3 Test") addtext(Sample, Girls) keep(d)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes append 
* reduced form for gr 3 non-cog 
reg hi d r dxr if f==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("Gr 3 High NC") addtext(Sample, Girls) keep(d)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes append 

* 2SLS for GEM in Gr 6
xi: ivreg gem6 (tr = d r dxr) r dxr if f==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("GEM Gr6") addtext(Sample, Girls) keep(tr)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes nor2 append 
* 2SLS for Algebra in Gr 6
xi: ivreg alg8 (tr = d r dxr) r dxr if f==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("Alg Gr8") addtext(Sample, Girls) keep(tr)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes nor2 append 
* 2SLS for Gr 6-8 Peer Quality
xi: ivreg peer_g35fcat_g68 (tr = d r dxr) r dxr if f==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("Peer Qual") addtext(Sample, Girls) keep(tr)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes nor2 append 
* 2SLS for No Suspensions in Gr 6-8 
xi: ivreg no_susp_ms (tr = d r dxr) r dxr if f==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("No Susp MS") addtext(Sample, Girls) keep(tr)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes nor2 append 	

* 2SLS for gr 6-8 test scores 
xi: ivreg fcat678_avgany (tr = d r dxr) r dxr if f==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("Gr 6-8 Test") addtext(Sample, Girls) keep(tr)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes nor2 append 
* 2SLS for gr 6-8 test scores 
xi: ivreg fcat678_math (tr = d r dxr) r dxr if f==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("Gr 6-8 Math") addtext(Sample, Girls) keep(tr)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes nor2 append 
* 2SLS for gr 6-8 test scores 
xi: ivreg fcat678_read (tr = d r dxr) r dxr if f==1, cluster(schid)
outreg2 using "${out}/table_C2.xls", excel ///
	cti("Gr 6-8 Read") addtext(Sample, Girls) keep(tr)  ///
	alpha(0.01, 0.05, 0.10) symbol(**, *, +) ///
	bdec(2) sdec(2) nocons nonotes nor2 append 
	
********************************************************************************
*** Appendix Table A10
********************************************************************************
	
use "${input}planb_rdsmpl.dta", clear

gen x=r+116 // rescale running variable

* create shorter names 
rename peer_g35fcat_g68_math pq_g35fcat_g68_math 
rename peer_g35fcat_g68_lang pq_g35fcat_g68_lang

* open table shell 
file close _all
file open table using "$out\summary_pval_all.csv", write replace
file write table "var,late_m,,late_f" _n // 9 columns

* loop through the set of outcomes:
foreach var in gha gem6 pq_g35fcat_g68_math pq_g35fcat_g68_lang alg8 no_susp_ms peer_g35fcat_hs_math peer_g35fcat_hs_lang math_gpa_hs lang_arts_gpa_hs gpa_hs num_ap_course fcat678_avgany fcat678_math fcat678_read maxpsattotpct maxpsatmathpct maxpsatreadpct collot {
	
	* LATE
	xi: ivreg `var' (gifted = d r dxr) r dxr if ${bw8} & m==1, cluster(schid)
	local late_m = _b[gifted]
	local late_m_se = _se[gifted]
	
	test gifted
	local p_val_m = r(p)
	
	local sig_m ""
	if `p_val_m'<.1 local sig_m "+"
	if `p_val_m'<.05 local sig_m "*"
	if `p_val_m'<.01 local sig_m "**"
	
	xi: ivreg `var' (gifted = d r dxr) r dxr if ${bw8} & f==1, cluster(schid)
	local late_f = _b[gifted]
	local late_f_se = _se[gifted]
	
	test gifted
	local p_val_f = r(p)
	
	local sig_f ""
	if `p_val_f'<.1 local sig_f "*"
	if `p_val_f'<.05 local sig_f "**"
	if `p_val_f'<.01 local sig_f "***"
	
	**************  ADD ROW TO TABLE *****************
	display "`var'"

	* rows for point estimates
	
	file write table "`var'"
	
	* rows for p-values
	
	* male results
	file write table "," (string(`p_val_m' ,"%15.3fc")) ""
		
	file write table ","
	
	* female results
	file write table "," (string(`p_val_f' ,"%15.3fc")) ""
	
	file write table ","
	
	file write table _n // end estimate row

}

file close table // close table

* clear any existing data
clear

* Load the CSV file
import delimited "$out\summary_pval_all.csv", clear

keep late_m
rename late_m pval

* Display summary information
display "***********************************"
display "Successfully loaded data from summary_pval_all.csv"
display "Number of p-values loaded: " _N
summarize pval
display "***********************************"

* run Anderson code
local totalpvals = r(N)

* Sort the p-values in ascending order and generate a variable that codes each p-value's rank
quietly gen int original_sorting_order = _n
quietly sort pval
quietly gen int rank = _n if pval != .

* Set the initial counter to 1 

local qval = 1

* Generate the variable that will contain the BH (1995) q-values

gen bh95_qval = 1 if pval != .

while `qval' > 0 {
	* Generate value qr/M
	quietly gen fdr_temp = `qval' * rank / `totalpvals'
	* Generate binary variable checking condition p(r) <= qr/M
	quietly gen reject_temp = ( fdr_temp >= pval ) if fdr_temp != .
	* Generate variable containing p-value ranks for all p-values that meet above condition
	quietly gen reject_rank = reject_temp * rank
	* Record the rank of the largest p-value that meets above condition
	quietly egen total_rejected = max( reject_rank )
	* A p-value has been rejected at level q if its rank is less than or equal to the rank of the max p-value that meets the above condition
	replace bh95_qval = `qval' if rank <= total_rejected & rank != .
	* Reduce q by 0.001 and repeat loop
	quietly drop fdr_temp reject_temp reject_rank total_rejected
	local qval = `qval' - .001
}
	
quietly sort original_sorting_order

* Save the FDR-adjusted results
export delimited using "${out}/table_a10_col3.csv", replace

clear

* Load the CSV file
import delimited "$out\summary_pval_all.csv", clear

keep late_f
rename late_f pval

* Display summary information
display "***********************************"
display "Successfully loaded data from summary_pval_all.csv"
display "Number of p-values loaded: " _N
summarize pval
display "***********************************"

* run Anderson code
local totalpvals = r(N)

* Sort the p-values in ascending order and generate a variable that codes each p-value's rank
quietly gen int original_sorting_order = _n
quietly sort pval
quietly gen int rank = _n if pval != .

* Set the initial counter to 1 

local qval = 1

* Generate the variable that will contain the BH (1995) q-values

gen bh95_qval = 1 if pval != .

while `qval' > 0 {
	* Generate value qr/M
	quietly gen fdr_temp = `qval' * rank / `totalpvals'
	* Generate binary variable checking condition p(r) <= qr/M
	quietly gen reject_temp = ( fdr_temp >= pval ) if fdr_temp != .
	* Generate variable containing p-value ranks for all p-values that meet above condition
	quietly gen reject_rank = reject_temp * rank
	* Record the rank of the largest p-value that meets above condition
	quietly egen total_rejected = max( reject_rank )
	* A p-value has been rejected at level q if its rank is less than or equal to the rank of the max p-value that meets the above condition
	replace bh95_qval = `qval' if rank <= total_rejected & rank != .
	* Reduce q by 0.001 and repeat loop
	quietly drop fdr_temp reject_temp reject_rank total_rejected
	local qval = `qval' - .001
}
	
quietly sort original_sorting_order

* Save the FDR-adjusted results
export delimited using "${out}/table_a10_col6.csv", replace 
 

